Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are C# properties actually Methods?

Tags:

c#

.net

oop

Till now, I was under the impression that Properties & Methods are two different things in C#. But then I did something like below.

enter image description here

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.

like image 754
yogi Avatar asked Apr 16 '14 07:04

yogi


People also ask

Are C and C++ same?

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.

Are C and C# same?

C language supports procedural programming. Whereas C# supports object oriented programming.

Is C# same as C++?

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.


2 Answers

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'

like image 36
p.s.w.g Avatar answered Sep 20 '22 15:09

p.s.w.g


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.

like image 141
dcastro Avatar answered Sep 18 '22 15:09

dcastro