IskanderRaimbayev IskanderRaimbayev - 10 months ago 53
C# Question

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

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?


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.