tags:

views:

315

answers:

8

In C# do properties need to reference private member variables, or can I just declare the properties and use them directly in the class code?

If the former is the best practice, then does that rule out using C# property short-hand? I.e.

public string FirstName { get; set; }
A: 

They do not need to reference private member variables. You can use them directly in the class.

jchapa
+26  A: 

Properties, when implemented like this:

public string FirstName { get; set; }

Automatically create a private member variable (the compiler does this for you), so you don't have to worry about it. This will behave exactly the same as if you do:

private string firstName;
public string FirstName { 
    get { return firstName; }
    set { firstName = value; }
}

There is no reason not to use the automatic properties ( { get; set; } ). The provide the same advantages as making your own private member variable.

In addition, if you later decide you need to do extra processing (for example, if you decide to implement INotifyPropertyChanged in your property setter), you can add this without changing your public API, but putting a backing field in manually.

Reed Copsey
+1 Good explanation
jchapa
There's no advantage over making your own trivial property - but you can't make a genuinely read-only property (i.e. *no* setter, not even a private one) backed by a read-only variable using automatically implemented properties :(
Jon Skeet
Very true. There are reasons to use manual properties over auto-implemented ones (read-only properties are one reason), but for many uses, the auto-props are very nice, and much nicer to type.
Reed Copsey
You can do something like `public string FirstName { get; private set; }`. It wont inherently protect a class' members if someone gets the instance, but it works great for basic types.
envalid
Jon was talking about doing public string FirstName { get { return something; } }, where something is read-only, and there is NO setter whatsoever. This is one case auto-properties don't handle.
Reed Copsey
I didn't realize it also set up the private variable, thanks for the illumination!
alchemical
Another reason to use public properties over public members is for reflection. Members and Properties are handled differently and if you use reflection, or tools that do (certain mocking and ORM frameworks) they won't always handle public members very well.
Jason Hernandez
I just tried this in Visual Studio and intellisense is not showing the existence of the private variable ("firstname"). Any idea what could be going on?
alchemical
What version of C# (.net). I know auto properties are fairly new...think it is C# 3 or Greater.
JonH
@LuftMensch: It isn't actually called firstName (it's called "<FirstName>k__BackingField"), and is "hidden" in intellisense for you. That's just what the compiler does behind the scenes, to make your life easier. In terms of use, though, it's the same as if you create it yourself.
Reed Copsey
ok cool, got it.
alchemical
+1 for a clear, concise explanation.
David Robbins
A: 

Hey,

C# can reference private variables as in:

public class A
{
    private string _b;

    public string B
    {
        get { return _b; }
        set { _b = value; }
   }
}

The get;set; designation is automatic properties which when compiled will generate the private variable for you, as a way to make it easy to setup your code.

Brian
A: 

Properties do not need to reference private member variables. It is best practice, though, to have them do so. You can think of properties as methods if it makes it easier to understand. You can run code inside of them. You can return whatever you want. You can call methods and use private member variables. You can even simply return a constant.

I use private member variables in almost all cases. It allows me to create a readonly property, or to provide some rules to those outside my class of getting or setting properties that my class doesn't have to follow.

Gabriel McAdams
A: 

To add on to Reed's answer, inside of your code (within the class itself) the member functions should adhere to this and actually use the Property rather then the actual private member. For instance if you had this:

public string FirstName { get; set; }

And you had a strange method called public char GetFirstLetter() that returned the first letter in a person's first name you'd want to do it like this:

 public char GetFirstLetter()
        {
            return FirstName[0];
        }

Instead of actually using your private variable. When you set a property a programmer may have written code to set it in a particular manner. So it only makes sense to simply use that property within your class methods.

JonH
+2  A: 

Properties created like this

public String Caption{ get; set; }

this will be compiled as

[CompilerGenerated]
private string <Caption>k__BackingField;

public string Caption
{
    [CompilerGenerated]
    get
    {
        return this.<Caption>k__BackingField;
    }
    [CompilerGenerated]
    set
    {
        this.<Caption>k__BackingField = value;
    }
}

The above code is extracted after compilation using reflector tool.

Balaji
A: 

if you use like

public string FirstName { get; set; }

compiler will automatically adds getters and setters for this property automatically.it not a bad practice.

Here is the proof

alt text

if you declare

private string firstName;
        public string FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }

like this also compiler will takes it as

alt text

so its not ruled out... :)

anishmarokey
A: 

Using properties is the best way to provide a method of control and security to the attributes in a class, always keep the attributes private if possible.

Jamie Keeling