Question

I have a readonly property which returns a string, say "my string", I am confused now by the following two methods:

(1)

 public string MyProperty
    {
       get 
       {
           return "my string"
        }
     }

(2)

private string myString = "my string";

public string MyProperty
{
   get
   {
        return myString;
   }
 }

so in other places of my code, if I use, say

 string b = MyProperty;  // b should be "my string" 

I would like to ask whether these two ways are both correct? or which one is preferred to the other? Thank you in advance !!!

Was it helpful?

Solution 2

Well, because the main purpose of properties in OOP is to hide implementation details the prefer way to do it is using option 2...using a backing field. So, syntactically, both approaches are correct, but design-wise, approach 2 is the correct way to do it

OTHER TIPS

You are talking about different things here.

A. This is a property that will ALWAYS return the hardcoded string value. Meaning that the way you have it written does not let you change that value under any circumstances.

B. With this implementation code, outside your class can never change the value via the MyProperty getter. However, code from within your class can change the value by changing the myString variable.

With backed field you can change the property value from within the class by changing the field. That's the main difference.

If you need your property to be really read only you can add readonly modifier to the field, and it will be more like your first solution.

Yes C# has many ways of doing things. However, your code really doesn't show the intent that the property is readonly. For something like this I would use constant.

public const string MyProperty = "my string";

If the property is read only to the outside world, but is manipulated privately by the class, then I suggest:

public string MyProperty { get; private set; }

If you're changing insde the class then it should be a property, if it's going to be the same value for the life of the app its a const.

const string MyString = "my string";

If you're changing;

public string MyString {get; private set; }

then internally,

MyString = "my string"; 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top