Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are Automatic Properties in C# and what is their purpose?

Could someone provide a very simple explanation of Automatic Properties in C#, their purpose, and maybe some examples? Try to keep things in layman's terms, please!

like image 957
dennis Avatar asked May 14 '11 12:05

dennis


People also ask

What are properties and methods in C#?

C# properties are class members that expose functionality of methods using the syntax of fields. They simplify the syntax of calling traditional get and set methods (a.k.a. accessor methods). Like methods, they can be static or instance.

What is full property in C#?

Property in C# is a member of a class that provides a flexible mechanism for classes to expose private fields. Internally, C# properties are special methods called accessors. A C# property have two accessors, get property accessor and set property accessor.

What is AC property?

A Class C property is one that is older (typically 30+ years old), in fair to poor condition, and typically not as well-located as a Class A or Class B building. They are considered to be the “riskiest” investment, but in turn, offer some of the best potential cash-on-cash returns.


2 Answers

Automatic Properties are used when no additional logic is required in the property accessors.
The declaration would look something like this:

public int SomeProperty { get; set; } 

They are just syntactic sugar so you won't need to write the following more lengthy code:

 private int _someField;  public int SomeProperty   {     get { return _someField;}     set { _someField = value;}  } 
like image 59
Stecya Avatar answered Oct 05 '22 05:10

Stecya


Edit: Expanding a little, these are used to make it easier to have private variables in the class, but allow them to be visible to outside the class (without being able to modify them)

Oh, and another advantage with automatic properties is you can use them in interfaces! (Which don't allow member variables of any kind)

With normal properties, you can do something like:

private string example; public string Example  {     get { return example; }     set { example = value; } } 

Automatic properties allows you to create something really concise:

public string Example { get; set; } 

So if you wanted to create a field where it was only settable inside the class, you could do:

public string Example { get; private set; } 

This would be equivalent to:

private string example; public string Example  {     get { return example; }     private set { example = value; } } 

Or in Java:

private String example;  public String getExample() {     return example; }  private void setExample(String value) {     example = value; } 

Edit: @Paya also alerted me to:

  • http://msdn.microsoft.com/en-us/library/bb384054.aspx
  • http://weblogs.asp.net/dwahlin/archive/2007/12/04/c-3-0-features-automatic-properties.aspx
like image 22
Darkzaelus Avatar answered Oct 05 '22 06:10

Darkzaelus