Search code examples
c#classinstantiation

Class instantiation C#


I'm beginner in C#.

Every time I created Constructor in my class to instantiate class.

class OtherClass
{
    void Main()
    {
        MyClass myClass = new MyClass();
    }
}

class MyClass
{
    public string text;
    public int num;

    public MyClass()
    {
        text = "something";
        num = 12;
    }
}

But today i saw new variant for me

class OtherClass
{
    void Main()
    {
        MyClass myClass = new MyClass { num = 12, text = "something" };
    }
}

class MyClass
{
    public string text;
    public int num;
}

Can somebody explain difference?

P.S Sorry for my English.


Solution

  • This is standard C# - it creates the class and then assigns values to properties.

    You should read the C# language specs.

    Technically this is identical to:

    var myClass = new MyClass ();
    myCVlass.num = 12;
    myClass.text = "something";
    

    Just syntactic sugar that i.e. VS will recommend you in code analysis automatically as simplified syntax.

    The explanation in the documentation is under this link.