Home > database >  What is the difference betwen initializing an instance of class and initializing the class itself?
What is the difference betwen initializing an instance of class and initializing the class itself?

Time:01-08

C# documentation Introduction to C# states

Constructors: Actions required to initialize instances of the class or the class itself.

Question: What is the difference betwen initializing an instance of class and initializing the class itself?

It is unclear to me what the above statement means and what initializing an instance of a class and initializing the class itself even looks like in code. Any help is greatly appreaciated. Thanks.

CodePudding user response:

I'm pretty sure, although you're right that it's not very clear, that they refer to instance constructors and static constructors. The former is used to initialize members of the instance(non static) and the latter is used to initialize static fields.

public class SimpleClass
{
    // Static variable that must be initialized at run time.
    static readonly long baseline;

    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed.
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }

    // instance constructor initializing the non-static fields and properties
    public SimpleClass(int x, int y)
    {
        X = x;
        Y = y;
    }

    public int X { get; set; }
    public int Y { get; set; }
}
  •  Tags:  
  • Related