Sunny
Sunny

Reputation: 6346

C# property definition

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!

Upvotes: 1

Views: 2788

Answers (5)

lomaxx
lomaxx

Reputation: 115843

You can have

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

Which will make a readonly public property. If you think about it, having a private readonly setter on a public property doesn't really make sense because you're wanting the setter to be readonly which is a method, not a variable.

If you were to make the setter readonly, essentially what you're doing is denying any access whatsoever to setting the value of the property. This is why you need the backing field.

Upvotes: 0

ChrisBD
ChrisBD

Reputation: 9209

What's wrong with:

public class Employee
{

 private string nameField;
 public string Name 
 { 
  get
  {
    return this.nameField;
  }
 }
 public Employee(string name)
 {
   this.nameField = name;
 }

Upvotes: 2

DevinB
DevinB

Reputation: 8326

readonly applies to variables and not to methods. set is converted into a method by the compiler, and therefore the readonly attribute makes no sense.

In order to accomplish what you want you need.

public class Employee
{
   private readonly string _name;

   public string Name
   { 
      get
      {
         return _name;
      }
   }

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

Upvotes: 1

Ian P
Ian P

Reputation: 12993

If you're concerned with only setting the properties within the constructor of the class that you're currently within, just make it a property with a private setter and don't set it in the class.. it's not like you don't have control over that situation.

$0.02

Upvotes: 0

Danvil
Danvil

Reputation: 23031

Use

private readonly string name = Empty.String;
public string Name { get { return name; } }

Upvotes: 7

Related Questions