0

Beginners question: Is there any disadvantage to the following solution?

public string SomeProperty { get; private set; }

as in C# public variable as writeable inside the class but readonly outside the class

Because I definetly find it nicer, than:

string someProperty; 
public string SomeProperty{
    get { 
        return someProperty; 
    } 
}  

But why can't C# have something like

GetOnly string someProperty; 

which would do the same as the above? Wouldn't that be much easier to read and write?

Community
  • 1
  • 1
user1323995
  • 1,286
  • 1
  • 10
  • 16
  • 1
    To answer the question no their no disadvange in fact the trend is to do this and not the second option as far as Microsofts auto completion and tools like CodeRush go. – Bit Jul 29 '13 at 16:57
  • Also the short cut is "propg" and {hit tab twice} – Bit Jul 29 '13 at 16:58

2 Answers2

4

What would be the point of auto property like?

public Foo FooProperty { get; }

How would you set its value to something meaningful?

Following code:

public Foo FooProperty { get; private set; }

Clearly states that you may read it outside of the class and set it only inside the class.

empi
  • 15,755
  • 8
  • 62
  • 78
0

A public read only field would work but you'd only be able to modify it in the class constructor.

public readonly string SomeField;

public MyClass()
{
    SomeField = "SomeString";
}
cgotberg
  • 2,045
  • 1
  • 18
  • 18