views:

295

answers:

3

I have read about how in ASP.NET 3.5 you can declare properties in C#

public DateTime DisplayDate
{
     get;
}

instead of

private DateTime _displayDate
public DateTime DisplayDate
{
     get {return _displayDate;}
}

like this post explains.

My question is, within the class, how do I access the private variable?

For example instead of this

public MyClass(DateTime myDisplayDate)
{ _displayDate = myDisplayDate; }

What should I assign to? Is it the public property?

public MyClass(DateTime myDisplayDate)
{ DisplayDate = myDisplayDate; }

Is this Correct?

+3  A: 
public DateTime DisplayDate
{
     get; private set;
}

public MyClass(DateTime myDisplayDate)
{ 
    this.DisplayDate = myDisplayDate; 
}
Gregoire
+1  A: 

Automatic Properties like this (which aren't limited to ASP.NET) are there so you don't have to deal with the private field. If you want to set the property's value, use the property itself and add a private setter (so only your class can set it)

public DateTime DisplayDate
{
    get; 
    private set;
}
Bob
Thanks, that is helpful.
A: 

You always need to declare both the getter and the setter with c# 3.0 automatic properties - see the other answers - the trick is to mark the setter as private.

public Foo { get; private set; }
x0n