What is Auto-Implemented property in C# 3.0 | .Net Feature

C# Language Features, From C# 3.0 - .Net

Using Auto-Implemented/Automatic Properties in C#

Typically in C# 2.0, you would implement a property as shown below :-

    private string name;

    public string Name
        get { return name; }
        set { name = value; }

Using Auto-Implemented/Automatic Properties in C#

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic or field declaration is required in the property accessors. 

They also enable client code to create objects. When you declare a property the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

For Example:

public string Name

Or using even less space, like this:

public string Name { get; set; }

No field declaration, and no code to get and set the value of the field. All of that is handled automatically by the compiler, which will automatically create a private field and populate the get and set method with the basic code required to read and write the field.

If you auto-implement a property, it would be handy to be able to set a default value. Indeed, there is the System.ComponentModel.DefaultValueAttribute which you can set.

For Example:

 [DefaultValue("-New Object-")]
        public string MyString { get; set; }
        public int MyInt { get; set; }
        public int EnvelopeHeight { get; set; }
        public bool MyBool { get; set; }

No comments:

All Rights Reserved by Etechpulse © 2015 - 2016
Powered By Blogger

Contact Form


Email *

Message *

Powered by Blogger.