Are C# properties actually Methods?

前端 未结 4 1216
花落未央
花落未央 2020-12-04 20:54

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

4条回答
  •  旧时难觅i
    2020-12-04 21:27

    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'

提交回复
热议问题