Reputation: 1360
I have been creating methods for a program of mine and I am now refactoring some code and I find I am changing all methods I initially made from:
public static string updateTextBox(string textbox){.... return "";}
to
public static void updateTextBox(TextBox textbox){...textbox.Text = "";}
I am doing this as with there are several advantages: 1.) first method I can only return a string and I found that sometimes I need to add more outputs(e.g change colour of the Foreground if an IF statement fails), with the second method I just add a second parameter.
public static void updateTextbox(TextBox textbox1, TextBox textbox 2){...}
2.) I can exit code easily with second method
return;
with first method the only thing I found was, which can cause errors
return null;
3.) It looks a lot cleaner when calling these methods
textbox.Text = MethodClass.updateTextbox(TextBox textbox)
MethodClass.updateTextbox(TextBox textbox)
I am a noob with programming still, is there something wrong with refactoring my methods to void types?
Upvotes: 0
Views: 67
Reputation: 1
It all depends on your requirement, whether you want to return a value form method or not. so if you want to update a class member then it's not necessary to return a value from the method which you want to set in your textbox. and it's not necessary to pass class members in your method, these are already accessible in the method.
If it's a reference type variable instead of a class member, you can pass it as a parameter and modify it inside the method itself. and if you have a value type then you can pass it as ref
or out
parameter.
So I would again say, it all depends on your requirement.
you can use your return value in the method for your logic purpose. like if you have a method to check whether a number is a palindrome, so you will just return true or false, so in this case, the return type is useful. you could have plenty of scenarios where you want to return and where you don't want return value from a method.
If you have a method like DoSomething
, It is just a simple method(like int num = 1*2;
)and you don't care about its return value then you can use void type.
Upvotes: 1