Search code examples
c#constructor

Is there equivalent of initializer list in C#?


In C++, you can define constructor like this:

class Foo
{
    private:
        int x, y;
    public:
        Foo(int _x, int _y) : x(_x), y(_y)
        {
        }
};

The constructor automatically initializes x to _x and y to _y. This is convenient when initialize fields simply as constructor parameters.


Solution

  • In C# versions before 12 you would do:

    class Foo
    {
      int _x;
      int _y;
      public Foo(int x, int y) {
       _x = x;
       _y = y;
      }
    }
    

    With C# 12 you can do:

    class Foo (int x, int y);
    

    and x and y will be available to your whole class instance.

    Obviously your class will have more logic, and it will have a body like:

    class Foo (int x, int y)
    {
      // Logic that works with x and y
    }
    

    Another type in C# is called record that will expose the parameter as a public property too. Like this:

    record Foo (int X, int Y);
    
    Foo foo = new (10, 20);
    
    // foo.X will be 10 and foo.Y will be 20