Question

I have a class library project. I have a property there like below. It's not a read only property

 private   Int32 ABC  ;
public Int32   ABCD
        {
            set
            {
                this.ABC = value;
            }
            get
            {
                return this.ABC;
            }
        }

My question is, Is it necessary to declare the private variable for the same and the getter / setter ?

EDIT

I mean could it be like below ?

public Int32 ABCD {}
Was it helpful?

Solution

Automatic property declarations require the get; set; statements in the braces (which is what you had in your original question):

public Int32 ABCD { get; set; }

An empty property block isn't valid.

OTHER TIPS

Use auto-implemented properties introduced in C# 3.0 (VS 2008) or later.
http://msdn.microsoft.com/en-us/library/bb384054.aspx

public Int32 Abcd {get;set;}

The compiler creates the backing field for you. However it is anonymous and cannot be accessed. If later on you find the need to access the backing field, you can explicitly declare it and reimplement the getter and setter using that field without breaking your interface.

Use auto implemented property, It interduced from 2008 :

    public Int   ABCD
    {
        set;
        get;
    }

But difference is default value, i.e in property with backing field you can set a default value in variable but in this case default is .net defaults. (in fact you should initiate it in constructor for default value).

If you do the second choice, C# will create the first one for you.

Is it necessary to declare the private variable for the same and the getter / setter ?

If you mean is it necessary to use the private variable then yes, it is (unless you use the automatic method mentioned by BoltClock).You should keep in mind that it is a full code block, so you can do pretty much anything you like in there - although you should do it within reason, as you don't want anything that is going to slow down the access to the properties too much.

For example, there can be side effects to changing a property, i.e. another property may have to be updated, or you may have to notify that other properties have changed as well.

If you are not notifying or doing anything else, then the automatic getter/setter method is the quicker to develop (that is not claiming it is the fastest (or slowest) to execute though).

you can do like this

public string ABCD { get;set;}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top