Usher
Usher

Reputation: 2146

Best way to return the string

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

Answers (6)

d.moncada
d.moncada

Reputation: 17402

private const string _myString = "MyString";
public string GetMyString()
{
    return _myString;
}

Upvotes: 5

Nahum
Nahum

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

Jainendra
Jainendra

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

rekire
rekire

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

Yehuda Shapira
Yehuda Shapira

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

Azodious
Azodious

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

Related Questions