Friday, December 5, 2008

Auto-implemented properties in .NET (C#)

Auto-implemented properties are created using set and get accessor without any attributes.

class AccessorExample

{

private string _ProdName;

public string ProdName

{

get

{

return _ProdName;

}

set

{

_ProdName = value;

}

}

public double CostPrice;

//Auto-implemented property

public double discount { get; set; }

//Read-only property

public double EmpDisc { get; private set; }

}

The statement public double discount { get; set; } sets / gets the discount

and can be accessed by

AccessorExample AEx = new AccessorExample();

AEx.ProdName = "T-Shirt";

AEx.CostPrice = 12.34;

AEx.discount = 10;

Console.WriteLine(AEx.ProdName + " Costs " + AEx.CostPrice.ToString() + " before " + AEx.discount + "% discount" );

A property that has both a get accessor and a set accessor is a read-write property, a property that has only a get accessor is a read-only property, and a property that has only a set accessor is a write-only property.

public double EmpDisc { get; private set; } is a read-only property; value of EmpDisc cannot be set. Assigning a value to this property will throw the following exception

AEx.EmpDisc = 15;

The property or indexer 'CSharpSample.AccessorExample.EmpDisc' cannot be used in this context because the set accessor is inaccessible

[The property or indexer 'property/indexer' cannot be used in this context because the set accessor is inaccessible - CS0272]

For auto-implemented properties, the compiler creates a private, anonymous backing field can only be accessed through the property's get and set accessors.





No comments:

Post a Comment