Static Methods
A static method in a non-static class can be accessed without an instance of that class.
Consider the following two classes;
PersonandPet.Both a person and a pet has a birthday, so calculating the age is a common task.
However, the same method would need to be replicated in both classes as follows.
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DOB { get; set; }
public void PrintInfo()
{
Console.WriteLine("{0} {1}, Age: {2}", FirstName, LastName, GetAge());
}
public string GetAge()
{
var age = DateTime.Today.Year - DOB.Year;
return string.Format("{0} years", age);
}
}
public class Pet
{
public string Name { get; set; }
public DateTime DOB { get; set; }
public void PrintInfo()
{
Console.WriteLine("{0}, Age: {1}", Name, GetAge());
}
public string GetAge()
{
var age = DateTime.Today.Year - DOB.Year;
return string.Format("{0} years", age);
}
}However, if the
GetAge()method was marked asstaticin one of the classes, the other class could use the same method without having to create an instance of that class.In that case, however, that method won't be able to access the member variable of the class, and will need to be passed as a parameter.
Last updated