Properties – the basics

Properties in C# is a special type of methods called accessors, they are accessed as if they are public member fields but with read, write and compute the value.

Is is declared like a field but with a get and set blocks inside, get is to read the property value and must return the same property type, set is to write to the property, using an implicit parameter called value.

Typically properties read and write from/to fields,

 

but we can also declare properties without depending on a field “automatic properties – introduced in C# 3.0”, when an automatic property is use, the compiler generates a private field for this property.

 

From MSDN:

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Read Only Properties:

We can make a property read-only by not adding a set accessor to the property body:

We may also mark the set accessor as private, while this will prevent class consumers from changing the property value but this doesn’t mean that this property is a read only, it just means that the property set accessor is not accessible out side this class.

… And also note, that if we started to add a body for the get accessor, we will have to add a body for the set accessor as well, which may not make sense with read only purpose properties.

We can also make the property private field a readonly, which will make sure that the field will never change after initializing.

http://stackoverflow.com/a/3917805/20126

 

Starting from C# 6.0 we can declare a read only property as an expression-bodied property

Which can contain more logic:

 

Initializing properties:

To initialize a property we can do this using the container class constructor or give the property’s private field value on deceleration.

Starting from C# 6.0 we can initialize the property inline like this:

and it can be used on read only properties as well

 

Finally, It is highly recommended to read “Why Properties Matter“!

 

examples used

This entry was posted in Technical and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *