What was the name of the access set that allows you to set the value in the constructor?

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

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

Any ideas what KEYWORD is? I searched everything but it was hard to find get / set accessors in google.

+3
source share
4 answers

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

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

    public string Name 
    {
        get { return _name; }
    }
}
+10
source

The keyword privateallows you to set a property from anywhere in the class:

private set;

i.e:

public string Name {get; private set;}

If you also wanted it to be set from the inheritance class, you could use protected.

readonly, , .

+7

, READONLY .

+2

GenericTypeTea , , , .

, , , , .

, -

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

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

Source: https://habr.com/ru/post/1762942/


All Articles