Automatic properties
In this chapter you will learn:
- What is automatic properties and how to use automatic properties in C#
- How to use the automatic properties
Automatic property
The get
and set
accessors' logic can be added by C# compiler.
This kind of property is called Automatic property.
Compare the two versions of Rectangle
class
class Rectangle{//from j a va 2s .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.
Access automatic properties
The following code creates and accesses the automatic properties.
using System;//from j av a2s.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:
Home » C# Tutorial » Class