Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do automatic properties require both getters AND setters?

In C#, if I declare an auto-implemented property, why do I have to declare BOTH the get and set part?

i.e.

public string ThisWorks { get; set; }

public string ThisDoesnt { get; }

Isn't this just syntactic sugar - i.e. the compiler inserts a private field for the property? So why the problem?

Curious.

like image 354
Duncan Avatar asked Nov 26 '22 21:11

Duncan


1 Answers

If you didn't have a setter - then how would you ever set the property?

Incidentally, you can specify the accessibility, eg:

public string Foo
{
  get;
  private set;
}
like image 101
stusmith Avatar answered Dec 10 '22 21:12

stusmith