C# Automatic properties
In this chapter you will learn:
Description
A property usually has a getter and/or setter that reads and writes to a private field of the same type as the property.
An automatic property declaration instructs the compiler to provide this implementation.
Compare the two versions of Rectangle
class
class Rectangle{// w w w.ja v a2s. c o m
private int width;
public int Width{
get{
return width;
}
set{
width = value;
}
}
}
The following code creates an automatic property.
class Rectangle{
public int Width {get; set;}
}
C# will generate the backend private field which is used to hold the value of width.
Syntax
We can redeclare the first example in this section as follows:
public class Person
{ /*from w ww . j ava2 s .co m*/
...
public decimal Salary { get; set; }
}
The compiler automatically generates a private backing field of a compiler-generated name that cannot be referred to.
Example
The following code creates and accesses the automatic properties.
using System;//from w ww.ja v a 2s. c o m
public class MainClass
{
static string MyStaticProperty
{
get;
set;
}
static int MyStaticIntProperty
{
get;
set;
}
static void Main(string[] args)
{
// Write out the default values.
Console.WriteLine("Default property values");
Console.WriteLine("Default string property value: {0}", MyStaticProperty);
Console.WriteLine("Default int property value: {0}", MyStaticIntProperty);
// Set the property values.
MyStaticProperty = "Hello, World";
MyStaticIntProperty = 32;
// Write out the changed values.
Console.WriteLine("\nProperty values");
Console.WriteLine("String property value: {0}", MyStaticProperty);
Console.WriteLine("Int property value: {0}", MyStaticIntProperty);
}
}
The output:
Next chapter...
What you will learn in the next chapter: