Instance and Static
Instance members
- Data and function members that operate on the instance eg ints ToString() is a instance member of Integer class
- By default members in a type/class are instance members
Static Members
- Don’t operate on the instance of the type
- Operate on the type itself
Example
using System; namespace Rextester { public class Program { public static void Main(string[] args) { Panda p1 = new Panda ("Pan Dee"); Panda p2 = new Panda ("Pan Dah"); Console.WriteLine(p1.Name); Console.WriteLine(p2.Name); Console.WriteLine(Panda.Population); } } public class Panda { //instance field public string Name; //static field //set to all Panda instances public static int Population; //Constructor public Panda (string n) { //Assign the instance field Name = n; //Increment the static Population field Population = Population + 1; } } }
Static Class
– all its members must be static