Static Fields
They are also known as class static fields, static class variables or static member data.
These are useful when you want to define a value that applies to all objects of a given type.
Often used to keep a count of the number of objects that have been instantiated.
Often used to store a value that must be shared amoing all the instances.
public class Animal
{
private int _Age;
private static int _Count;
}
class Program
{
static void Main(string[] args)
{
Animal mydog = new Animal();
Animal mycat = new Animal();
mydog.Age = 2;
Animal._Count += 1;
System.Console.WriteLine(Animal.Total);
mycat.Name = "two";
Animal._Count += 1;
System.Console.WriteLine(Animal.Total);
System.Console.ReadLine();
}
}
Static Constructor
A static constructor allows you to control the initialisation of static variables.
A static constructtor will be called before a class is used.
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext