Reputation: 2146
I may get negative marks for this but still getting some comments from experts or suggestions is more knowledge to me, so here is my question.
Here I am returning a string
public static string mystring()
{
return "test";
}
Is there any best way to return the string or what is the draw back of my return?
Upvotes: 1
Views: 121
Reputation: 17402
private const string _myString = "MyString";
public string GetMyString()
{
return _myString;
}
Upvotes: 5
Reputation: 7197
will this string ever change its source? if you are sure it will always be hardcoded, just use constant.
const string mystring = "test";
if it might get its value from somewhere else in your class. property will be better
public string MyString
{
get {return "test";}
}
use the function only if this value will need some complex logic in the future. like been taken from database inputed by user and so on.
Upvotes: 3
Reputation: 25153
You can define a constant like myString
, instead of mystring function. So whenever you want to use this string just call that constant.
public const string myString = "test";
Upvotes: 1
Reputation: 47985
I don't see that there is a problem with it. I would do it the same way.
A second way would be to use properties:
public static string mystring {
get { return "test"; }
}
Upvotes: 1
Reputation: 8630
Technically, there is no problem.
However, it's preferable to stick to conventions, and use a constant.
I'm sure there's no need to explain the need to stick to conventions and standards!
EDIT: If you feel that one day there may be a need to use some internal logic before returning the string, then perhaps using a method is correct.
Upvotes: 1
Reputation: 13882
Declare a constant and return that from method.
if you are returning same value from multiple methods, updating the value at one place will be easier than to update in each method.
Upvotes: 1