Wednesday 8 March 2017

Static vs Instance

Static properties or function or methods are shared by all instances of their class, they don't get created or instantiated they're just always there.

class Person
{
    static int _runningID = 0;
    public int Id { get; } = _runningID++;
    public string Name { get; set; }

    public void SayHi() {
        Console.WriteLine($"Hi my name is {Name}");
    }
    static Type GetMyType()
    {
        return typeof(Person);
    }

}

in the above class we see that if we have to instances of person they'll share their static members but have instances of their own non static members.

    class Program
    {
        static void Main(string[] args)
        {
            var p1 = new Person { Name = "Pawel" };
            var p2 = new Person { Name = "Ian" };

            p1.SayHi();
            p2.SayHi();

            Console.WriteLine(Person.GetMyType());
        }

    }

and you can see from the above we call instance and static members, instance members have to be called from the instantiated instance of a class whereas Static ones must be called from the class definition.