Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 calls instance.

Obviously your class has 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading