Today, I was just thinking what if I had read/heard a theoretical point from somewhere/someone that properties are actually methods internally and they are prefixed by get_
and set_
for get and set accessors respectively but wanted to validate it practically.
I am sure now you’ll think of saying: dude go and see IL for that assembly using ILDASM or similar tool. But let's assume we didn’t have any of these tools or knowledge of reading IL code. How else can we suppose to check/validate this theoretical point?
If you are an experienced good C# programmer, I am sure you already know the solution.
Other way to put this point is, let's assume that a C++ guy is writing a C# code and has declared a property called SomeProperty
and also wants to write a method get_SomeProperty()
due to C++ coding style, but fails to compile his code because compiler issues some weird error which he can’t understand why.
In both cases, I would like to just give a small explanation with the code here:
1: static string SomeValue
2: {
3: get;
4: set;
5: }
6:
7: public string get_SomeValue()
8: {
9: return null;
10: }
11:
12: public string get_SomeValue(string someValue)
13: {
14: return null;
15: }
In the above code, compiler issues error for the explicit method specified by developer string get_SomeValue()
. The error is as shown:
Error 1 Type ‘ConsoleApplication2.Program’ already reserves a member called
‘get_SomeValue’ with the same parameter types
This is because the compiler has already generated a method with the same signature for the property which is defined in the code. Since it is a method, we can overload it and compiler doesn’t have any issues with it. You also get the same error if you write 2 methods with the same signature in your code as well.
Thus, we can prove that the theoretical point on properties are methods having get_
and set_
prefixes are true
without looking into IL.
Thanks for reading!