Behind the Scenes Look at C#: Properties continued - Static Properties
(Page 3 of 4 )
Like static methods, static properties have defined on the class itself, not on an instance of the class. Sometimes you will find yourself in a situation where you have an attribute that has a class scope (a static field), which means that the field value is shared between all the instances of the class. For the same reasons that we have used properties with private fields, we will use a public static method with a private static field.
You access the property using the class identifier (not in the form of instance.property). A static property accesses only a static field. This makes sense because the get/set methods need the this pointer to access the field. A static property doesn't have a pointer to this because it has a class scope. So an instance property can access a static field because static data are exposed to static and instance methods. The following updated version of the Worker example illustrates the use of static properties.
using System;
namespace property
{
class Class1
{
static void Main(string[] args)
{
try
{
Worker.Department = "IT";
Worker w1 = new Worker();
w1.FirstName = "Michael";
w1.LastName = "Youssef";
Console.WriteLine(w1);
Console.WriteLine();
Worker w2 = new Worker();
w2.FirstName = "Maria";
w2.LastName = "Meleka";
Console.WriteLine(w2);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
public class Worker
{
private string firstName;
private string lastName;
private static string department;
public string FirstName
{
get
{
return this.firstName;
}
set
{
if(value == String.Empty)
{
throw new ArgumentNullException();
}
else
{
this.firstName = value;
}
}
}
public string LastName
{
get
{
return this.lastName;
}
set
{
if(value == String.Empty)
{
throw new ArgumentNullException();
}
else
{
this.lastName = value;
}
}
}
public static string Department
{
get
{
return department;
}
set
{
if(value != "IT")
{
throw new ArgumentException("All Workers must be in the IT Department");
}
else
{
Worker.department = "IT";
}
}
}
public override string ToString()
{
return firstName +" "+lastName+" is working in "+department;
}
}
}
The result that you will get in the console window is this:

We have declared the department private field as static, and the department property as static too. Note that by using a static property instead of a public static field we are able to do our data validation and throw exceptions, as we have done with the instance properties.
Next: Read or Write Properties >>
More C# Articles
More By Michael Youssef