I know that when we use properties in C#, the compiler always generate getters and setters for them in MSIL (i.e., get_PropertyName and set_PropertyName), for example, consider the following piece of code:
class Program
{
class Test
{
public string Name { get; set; }
}
static void Main(string[] args)
{
//Here I'm using reflection to inspect methods of Test class
Type type = typeof(Test);
foreach (var item in type.GetMethods())
{
Console.WriteLine(item.Name);
}
}
}
This program will produce output with the methods of Test
, among which there will be get_Name
and set_Name
- the getter and setters I was talking about.
In my understanding then, if getters and setter are created "behind the scenes" then there should be a backup field created as well from which/to which the getters and setter get/set values.
So, from the previous example, I can use reflection to inspect fields for Test class, like that:
static void Main(string[] args)
{
Type type = typeof(Test);
foreach (var item in type.GetFields())
{
Console.WriteLine(item.Name);
}
}
The ouput of this program is empty, I assume this is because the backup field that was created has private
access, so we cannot see it. But since I don't know how to check it, can you please let me know if a backup field always get created (even if we have a simple property with only get;
and set;
) ?
But since I don't know how to check it, can you please let me know if a backup field always get created (even if we have a simple property with only get; and set; ?
An automatically implemented property, e.g.
public int ReadWriteProperty { get; set; }
public int ReadOnlyProperty { get; }
will indeed always have a backing field generated by the compiler. But if you provide your own implementation of the getter/setter, then the compiler won't generate a field:
public int Zero => 0;
public int IgnoresSetter
{
get { return 10; }
set { /* Meh. Whatever you say, I'm still going to return 10 in the getter... */ }
}
Neither of those will cause a field to be generated.
See more on this question at Stackoverflow