i 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With