Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Shorthand Property Question

Tags:

c#

properties

So here is a bit of syntax that I have never seen before, can someone tell me what this means? Not sure if this is supposed to be some shorthand for an abstract property declaration or something or what.

public Class1 myVar { get; set; } 

For what its worth, Class1 is an abstract class.

like image 881
pfunk Avatar asked Mar 26 '09 19:03

pfunk


2 Answers

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

// Auto-Impl Properties for trivial get and set     public double TotalPurchases { get; set; }     public string Name { get; set; }     public int CustomerID { get; set; } 
like image 81
alex Avatar answered Sep 21 '22 16:09

alex


This is the syntax to let the compiler create a (hidden) field for you.

Also very useful is:

public Class1 myVar{ get; private set; } 
like image 28
laktak Avatar answered Sep 21 '22 16:09

laktak