With automatic properties, you can not manually declare a private member variable and write Get/set logic, instead, the compiler will automatically generate a private variable and the default Get/set operation for you. The private variables that the system generates for you are not visible in the IDE, as shown in the following diagram:
Of course, if you want some of the attributes to be assigned or to take a logical check, automatic properties are not for you.
After we compile the above code and then use Reflector to decompile it, we can see that the attribute in the above code becomes the following code: The private variable that the compiler gives us is obviously not so easy to duplicate.
[Compilergenerated] private String <>k__AutomaticallyGeneratedPropertyField0;
public string Name { [Compilergenerated] Get { Return this.<>k__automaticallygeneratedpropertyfield0;
} [Compilergenerated] Set { this.<>k__automaticallygeneratedpropertyfield0 = value; } }
|
Note: If you only want the property to have a get or set method, these situations will not be able to use the automatic properties, you need to write yourself. Otherwise it will be reported as the following error:
"ConsoleApplication1.MyClass.Name.set" must declare a body because it are not marked abstract or extern. Automatically implemented properties must define both get and set accessors. |
But get and set access levels are different, such as one is public and one is internal, you can write in the following way without reporting an error.
public int ID {get; internal set;} |