Till now, I was under the impression that Properties
& Methods
are two different things in C#. But then I did something like below.
and this was an "Eye Opener" to me. I was expecting one property stringProp
and one method stringProp
but instead I got this.
Why this happened? can someone explain please.
C++ is a superset of C, so both languages have similar syntax, code structure, and compilation. Almost all of C's keywords and operators are used in C++ and do the same thing. C and C++ both use the top-down execution flow and allow procedural and functional programming.
C language supports procedural programming. Whereas C# supports object oriented programming.
Both C++ and C# are object-oriented languages, although C++ is considered a harder language to work with. Both of them can be used in web and desktop applications, but C# is much more popular now for both applications.
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'
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.
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