Joan Venge
Joan Venge

Reputation: 331290

What was the name of the set accessor that only lets the value to be set in the constructor?

public class MyClass
{
  public string Name {get; KEYWORD set;}

  public MyClass(string name)
  {
    this.Name = name;
  }
}

Any ideas what the KEYWORD was? I searched all over but it's hard to find the get/set accessors in google.

Upvotes: 3

Views: 223

Answers (4)

djdd87
djdd87

Reputation: 68506

The private keyword allows the property to be set from anywhere within the class:

private set;

I.e:

public string Name {get; private set;}

If you also wanted to allow it to be set from an inheriting class, you could use protected instead.

You could use the readonly keyword to only allow the property to be set once, but it cannot be used on auto-implemented properties.

Upvotes: 7

Brad Cunningham
Brad Cunningham

Reputation: 6501

like GenericTypeTea said you are probably looking for the private keyword.

However, just to be clear, making your set accessors private doesn't restrict it to ONLY the constructor but anyway within the class.

To make the property ONLY settable from the constructor you want something like this

public class MyClass
{
  private string name;
  public string Name {get { return name;} }

  public MyClass(string nameString)
  {
    name = nameString;
  }
}

Upvotes: 1

iChaib
iChaib

Reputation: 479

I know that using the READONLY keyword on a field let you write in this field once and it must be only in the constructor.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039238

If you want to be able to set the value only in the constructor I would recommend you the readonly keyword:

public class MyClass
{
    private readonly string _name;
    public MyClass(string name)
    {
        _name = name;
    }

    public string Name 
    {
        get { return _name; }
    }
}

Upvotes: 10

Related Questions