简体   繁体   中英

Proper Syntax for C# Properties

Per the MSDN documentation , the following syntax is used:

// A read-write instance property:
public string Name
{
    get { return name; }
    set { name = value; }
}

However, the following code is generated by VS2010 automatically for a new library class:

public string Name
{
    get
    {
        String s = (String)ViewState["Name"];
        return ((s == null) ? String.Empty : s);
    }

    set
    {
        ViewState["Name"] = value;
    }
}

When is it appropriate to use the ViewState syntax over the shorter example shown on MSDN?

ViewState is a feature of ASP.Net server controls that persists information across postbacks.

For simple properties that aren't in a server control, you should use an auto-implemented property :

public string Name { get; set; }

The first stores the value in a private property field inside the class, while the second (tries to) store the actual value in the ViewState.

So the 2nd is only possible when you are talking about ASP controls with viewstate enabled, which is a narrow subset of all possible cases.

A C# property is just a piece of syntactic sugar. This structure

public Foo MyValue { get ; private set ; }

is exactly as if you coded:

private Foo _myValue ;
public Foo
{
  get
  {
    return _myValue ;
  }
  private set
  {
    this._myValue = value ;
  }
}

In either case, the code that actually gets generates is pretty much this:

private Foo _myValue ;
public Foo MyValue_get()
{
  return this._myValue ;
}
private Foo MyValue_set( Foo value )
{
  this._MyValue = value ;
}

If you opt to instantiate your own getter/setter, then what happens in the body of the getter/setter is entirely up to you. There is no "right" or wrong: it's dependent on the needs of your program.

With respect to ViewState , ViewState is a piece of ASP.Net. It has little do with properties one way or another. You example just exposes a ViewState item as a public read/write property.

The difference between the two is that one is just plain old C# property providing access to a (most likely) privately scoped variable in your class.

The other one is returning a value recovered from ASP.NET's ViewState.

These are two different things altogether.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM