32

Class A uses an initializer list to set the member to the paramter value, while Class B uses assignment within the constructor's body.

Can anyone give any reason to prefer one over the other as long as I'm consistent?

class A
{
    String _filename;

    A(String filename) : _filename(filename)
    {
    }
}


class B
{
    String _filename;

    B(String filename)
    {
        _filename = filename;
    }
}

4 Answers 4

98

The first one is not legal in C#. The only two items that can appear after the colon in a constructor are base and this.

So I'd go with the second one.

1
  • 23
    Thank you, coming from C++ I was wondering whether Syntax A (member initialization list) was viable for C# too. Oct 12, 2015 at 16:41
19

Did you mean C++ instead of C#?

For C++, initializer lists are better than assignment for a couple of reasons:

  • For POD types (int, float, etc..), the optimizer can often do a more efficient memcpy behind the scenes when you provide initializers for the data.
  • For non-POD types (objects), you gain efficiency by only doing one construction. With assignment in the constructor, the compiler must first construct your object, then assign it in a separate step (this applies to POD types as well).
0
12

As of C# 7.0, there is a way to streamline this with expression bodies:

A(String filename) => _filename = filename;

(Looks better with two fields though):

A(String filename, String extension) => (_filename, _extension) = (filename, extension);
1

C# has a feature called Object Initializer. You can provide values which the compiler will use to initialize the specified members, and call the default constructor. For this to work you need to have a public default constructor.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.