Why is it allowed to set a property that does not set anything in C #?

I was looking at the PRISM toolkit and I find many examples where they declare a public property with empty getters / setters, but they can still set the class instance property. How / why is this possible?

    public class ShellPresenter
    {
        public ShellPresenter(IShellView view)
        {
            View = view;

        }

        public IShellView View { get; private set; }
    }

//calling code
ShellPresenter sp = new ShellPresenter();

//Why is this allowed?
    sp.View = someView;
+3
source share
5 answers

They use the properties of C # auto. This is a convenience due to which the compiler creates a support field for you. private setmeans that the property is read-only from outside the class. So, if sp.View = someView;used outside the class, this will lead to a compiler error.

+8
source

This is a new feature in C # 3.0.

http://msdn.microsoft.com/en-us/library/bb384054.aspx

# 3.0 , .

+11

Decompiling your ShellPresenter with Red Gate.NET Reflector

public class ShellPresenter
{
// Fields
[CompilerGenerated]
private IShellView <View>k__BackingField;

// Methods
public ShellPresenter(IShellView view)
{
    this.View = view;
}

// Properties
public IShellView View
{
    [CompilerGenerated]
    get
    {
        return this.<View>k__BackingField;
    }
    [CompilerGenerated]
    private set
    {
        this.<View>k__BackingField = value;
    }
  }
}
0
source

What you posted is not allowed if the object is not defined inside the class itself. Here is a sample code of what is and is not allowed.

   public interface IShellView
    {

    }
    public class View:IShellView
    {
    }

    //public class SomeOtherClass
    //{
    //    static void Main()
    //    {
    //        IShellView someView = new View();
    //        //calling code 
    //        ShellPresenter sp = new ShellPresenter();

    //        //Why is this allowed? 
    //        sp.View = someView;//setting a private set outside the ShellPresenter class is NOT allowed.
    //    }
    //}

    public class ShellPresenter
    {
        public ShellPresenter()
        {
        }
        public ShellPresenter(IShellView view)
        {
            View = view;

        }
        static void Main()
        {
            IShellView someView = new View();
            //calling code 
            ShellPresenter sp = new ShellPresenter();

            //Why is this allowed? 
            sp.View = someView;//because now its within the class
        }
        public IShellView View { get; private set; }
    } 
0
source

The C # compiler creates a backend field for you. This syntax has been introduced to support anonymous types (e.g. new { A = 1, B = "foo" })

-1
source

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


All Articles