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.
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;}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With