Anonymous Properties:

This is the new feature introduced in C# 3.0

Prior to C# 3.0, we have properties declared as below.

 

  class Test

    {

        private string MyName;

        public string Name

        {

            get

            {

                return MyName;

            }

            set

            {

                MyName = value;

            }

        }

    }

 There is no much logic inside the properties getters and setters; these are made short in C# by name Anonymous Properties as

   class Test

    {

        public string MyName { get; set; }

       

    }

 

Using Properties, we can restrict variable properties like ‘Read-Only (only getter)’, ‘Write only’ (Only setter). Read Write (Both getter & Setter).

I.e. Prior to C# 3.0, we can include either get or set or both.

But Anonymous Properties as a new feature in C# 3.0, we need to include both get and set while declaring the properties. But we can achieve the ‘Read-Only’ by declaring as

  class Test

    {

        public string MyName { get;private set; }

       

    }

||’ly we can achieve ‘Write Only’ property by declaring as

    class Test

    {

        public string MyName { private get; set; }

       

    }

If the property has both getter & setter of public type, one can think why to go for properties instead of public variables.

Here is a lay down of differences between variables & properties:

  • Variables have single line of declaration & single of piece of memory allocated for them. Whereas for properties, there are series of declarative statements and memory will be allocated for the whole block.
  • Custom manipulations cannot be done with variables, whereas properties can be done using setters and getters.
  • Unlike a variable, the value of a property might not correspond directly to a single item of storage. The storage might be split into pieces for convenience or security, or the value might be stored in an encrypted form. In these cases the Get procedure would assemble the pieces or decrypt the stored value, and the Set procedure would encrypt the new value or split it into the constituent storage. A property value might be ephemeral, like time of day, in which case the Get procedure would calculate it on the fly each time you access the property.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s