Static Classes
Objects cannot be created from a static class.
A static class may only contain static members and methods.
These are highly useful as classes that contain utility methods.
public class Program
{
static void Main(string[] args)
{
var person = new Person() { Name = "Sach", DOB = new DateTime(1981, 5, 21) };
Utility.PrintDetails(person.Name, Utility.GetAge(person.DOB));
var pet = new Pet() { Name = "Kitty", DOB = new DateTime(1990, 3, 21) };
Utility.PrintDetails(pet.Name, Utility.GetAge(pet.DOB));
}
}
public class Person
{
public string Name { get; set; }
public int Phone { get; set; }
public DateTime DOB { get; set; }
}
public class Pet
{
public string Name { get; set; }
public DateTime DOB { get; set; }
}
public static class Utility
{
public static string GetAge(DateTime dob)
{
var age = DateTime.Today.Year - dob.Year;
return string.Format("{0} years", age);
}
public static void PrintDetails(string name, string age)
{
Console.WriteLine("Name: {0}, {1}", name, age);
}
}Last updated