Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why property can be contain only setter in interface type in C#?

Tags:

c#

class

I wonder why in C# it is not allowed to use only { set } property in auto-generated property in class type like:

class Person {
    public string Name { set; } // Compile-time error
}

However, it is allowed in interface type:

interface IPerson {
    string Name {set;} //Allowed
}

I read similar question here, it is very rare practice - what I understand, but I wonder why CLR even allow to do it?

like image 659
Iskander Raimbaev Avatar asked Nov 29 '22 23:11

Iskander Raimbaev


2 Answers

For one simple reason. If you're using an Auto implemented property (Hidden private field generated). Then why would you need to set a value that you would never be able to get (and subsequently use).

For the Interface, you're not using an auto implemented property, it is just a contract specifying that the implementation class should have a string property named Name that should implement a Setter method. So, you can do this:

interface IPerson
{
    string Name { set; }
}

class Person : IPerson
{
    private string _name;
    public String Name
    {
        set { _name = value; }
    }
}

So in conclusion, the C# compiler is trying to prevent us from doing something that doesn't make any sense which is: Providing an auto set method for a private hidden field that can never be get.

like image 139
Zein Makki Avatar answered Dec 09 '22 20:12

Zein Makki


Because what is the point of a property you can assign a value to but have no way to observe it?

The following is perfectly legal

class Person {
    private string _name;
    public string Name { set { _name = value } }
}

The reason the auto property doesn't let you do it is because you could never get the value out after it was written, with a manual implemented property you have the chance to set the value to some other field.

The reason interfaces allow it is so the interface can describe manually implemented versions or auto implemented ones with public string Name {private get; set;}.

like image 35
Scott Chamberlain Avatar answered Dec 09 '22 19:12

Scott Chamberlain