Static Members
So far, we have used non-static fields in our classes
This means, that each instance of the class holds its own version of the field, and changing the value of it only affects that instance:
class MyAwesomeClass
{
public int MyProperty { get; set; }
}
class Program
{
static void Main(string[] args)
{
MyAwesomeClass instance1 = new MyAwesomeClass();
MyAwesomeClass instance2 = new MyAwesomeClass();
instance1.MyProperty = 100;
instance2.MyProperty = 200; // instance1.MyProperty is still 100
}
}
Static Members (continued)
Likewise, non-static class methods _have to _ be called through an instance:
class MyAwesomeClass
{
public void PrintText(string text) { Console.WriteLine(text); }
}
class Program
{
static void Main(string[] args)
{
MyAwesomeClass instance = new MyAwesomeClass();
instance.PrintText("Hello World"); // Outputs "Hello World"
MyAwesomeClass.PrintText("Hello World"); // Results in an error
}
}

Static fields are shared between all instances of a class
Let's declare "MyProperty" property with the __static __ keyword. Now it can be referenced through the class type name, but not through the instance, as shown below:
class MyAwesomeClass
{
public static int MyProperty { get; set; } = 100;
}
class Program
{
static void Main(string[] args)
{
MyAwesomeClass instance = new MyAwesomeClass();
Console.WriteLine(MyAwesomeClass.MyProperty); // Outputs "100"
Console.WriteLine(instance.MyProperty); // Results in an error
}
}

Static Members - Example
In this example, a static field is used for keeping count on how many times the class has been instantiated:
class Person
{
public static int totalPersons = 0;
private string name;
public Person(string personName) // Person Constructor
{
name = personName;
++totalPersons;
}
public void PrintInfo()
{
Console.WriteLine("This person is called " + name + ".");
Console.WriteLine("There are " + totalPersons + " persons total.");
}
}
Static Members - Example (continued)
Now let's instantiate a couple of persons and print their info:
class Program
{
static void Main(string[] args)
{
Person steve = new Person("Steve");
Person wendy = new Person("Wendy");
steve.PrintInfo();
wendy.PrintInfo();
}
}

Static Methods
Methods can also be static
What happens when you try to call a non-static method from a static method?
class Program
{
void PrintHelloName(string name)
{
Console.WriteLine("Hello, " + name);
}
static void Main(string[] args)
{
PrintHelloName(); // Will throw an error
}
}
