C# property definition

Posted by Sunny on Stack Overflow See other posts from Stack Overflow or by Sunny
Published on 2010-04-28T15:05:18Z Indexed on 2010/04/28 15:13 UTC
Read the original article Hit count: 296

Filed under:
|

For C# properties, I can do this:

public class Employee{

 public string Name { get; private set; }

 public Employee(string name){
  Name = name;
 }

}

which means that the Name property can be set within the class Employee & can be read publicly.

But, if I want to restrict the set to only within the constructors of the Employee class, I need to do:

public class Employee{
 public readonly string Name = String.Empty;
 public Employee(string name){
  Name = name;
 }
}

But, for this case, I had to change the property to a field.

Is there any reason this is not possible/allowed in C#:

public class Employee{
 public string Name { get; private readonly set; }
 public Employee(string name){
  Name = name;
 }
}

IMO this will allow us to have properties which can be set only in the constructor & does not require us to change properties to fields...

Thanks!

© Stack Overflow or respective owner

Related posts about c#

Related posts about programming-languages