Are C# properties actually Methods?
Solution 1:
Yes, the compiler generates a pair of get and set methods for a property, plus a private backing field for an auto-implemented property.
public int Age {get; set;}
becomes the equivalent of:
private int <Age>k__BackingField;
public int get_Age()
{
return <Age>k__BackingField;
}
public void set_Age(int age)
{
<Age>k__BackingField = age;
}
Code that accesses your property will be compiled to call one of these two methods. This is exactly one of the reasons why changing a public field to be a public property is a breaking change.
See Jon Skeet's Why Properties Matter.
Solution 2:
Strictly speaking, properties are not methods, although they are indeed supported by getter and setter methods (also called accessors). When you write code like this (provided you modify the code to remove the compile error mentioned below)
myFoo.stringProp = "bar";
The compiler actually generates IL code like this:
ldstr "bar"
callvirt foo.set_stringProp
Where set_stringProp
is the setter method for that property. In fact, if you so desired, you can invoke these methods directly via reflection.
However, the code sample you posted may look okay in Visual Studio's intellisense, but it will not compile. Try building the project and you will see an error like:
The type 'foo' already contains a definition for 'stringProp'
Solution 3:
This is visual studio intelicence issue, that picks by name. By the way your code will not compile even, due the name collision in the same type.
But you are right, that properties are methods at the end:
public class A {
public string Name {get;set;}
}
here Name
property is converted into 2 methods: get_Name()
and set_Name()
.
In fact, if you define class like this:
public class A {
public string Name {get;set;}
public string get_Name() {
return "aaa";
}
}
you will get compilation error, as there is already defined get_Name
(property)