Getter property only against getter and private setter

Are they the same?

public string MyProp { get; }

vs.

public string MyProp { get; private set; }

I mean that in both versions the property can be set in its own class, but is it only for other classes?

+4
source share
4 answers

public string MyProp { get; }- This is introduced in C # 6.0. . Such properties are called read-only automatic properties. Assignments to such members can only be performed as part of a declaration or in a constructor of the same class. You can read a detailed explanation about this in this MSDN article or in the Jon Skeet blog. As explained in this article, this property automatically solves four problems:

  • ( -)
  • ,

public string MyProp { get; private set; } - , , .

, auto-properties , auto-initialize, # 6.0:

public string MyProp { get; } = "You can not change me";

#:

private readonly string myProp = "You can not change me"
public string MyProp { get { return myProp ; } }

, # 6.0:

public string MyProp { get; }
protected MyClass(string myProp, ...)
{
    this.MyProp = myProp;
    ...
}

:

private readonly string myProp;
public string MyProp { get { return myProp; } }
protected MyClass(string myProp, ...)
{
    this.myProp = myProp;
    ...
}
+8

# 6.0:

public class MyClass
{
    public int MyProp1 { get; }
    public int MyProp2 { get; private set; }

    public MyClass()
    {
        // OK
        MyProp1 = 1;
        // OK
        MyProp2 = 2;
    }

    public void MyMethod()
    {
        // Error CS0200  Property or indexer 'MyClass.MyProp1' cannot be assigned to --it is read only
        MyProp1 = 1;
        // OK
        MyProp2 = 2;
    }
}

# :

1 'MyClass.MyProp1.get' , . get, set accessors.

+1

:

// C#, all versions
private readonly int _foo;
public int Foo
{
    get { return _foo; }
}

// C#, version 6+
// actually, this is the same as above, but backing field is generated 
// for you by compiler
public int Foo { get; }

: , , , getter, , :

typeof(SomeType).GetProperty("Foo").SetValue(bar, 1)

, , :

// this will work fine: typeof(SomeType).GetProperty("Foo").SetValue(bar, 1)
public int Foo { get; private set; }

: : get-method, - get-, set-methods.

+1

, . , " ".

readonly-backend:

private readonly string field;
public string MyProp { get { return this.field; } }

attemp . , # 6, :

public string MyProp { get; }

, , , - .

0

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


All Articles