c# function coding guideline [closed]
开发者_StackOverflow中文版Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this questioni need to pass values from one class to another and asked me what is the best way. What do you think?
a)
public string getValue(){
string returnValue;
ClassA myClass = new ClassA();
returnValue= myClass.getValue();
return returnValue;
}
b)
public string getValue(){
return new ClassA().getValue();
}
I don't know if there is a problem with b like bad programming style...
Thank you!
The compiler will almost certainly reduce "a" down to "b" anyway in release mode.
There is a case for adding intermediate variables if you are likely to want to debug with break-points at that location. But IMO "a" adds very little. I'd use "b".
Of course, you could also argue that the new ClassA()
instance adds very little, and a static method should be provided instead. And then at that point the method itself is providing very little, and the caller should just call the static ClassA.GetValue()
itself.
I'm assuming ClassA does something (a calculation, DB call, etc) and you want the result of that. One way would be to design ClassA as a static class, similar to this:
public static ClassA{
public static string GetValue(){
//magic happens here
}
}
Any other class could then simply call the method:
var myReturnValue = ClassA.GetValue();
精彩评论