When initializing in C# constructors what's better: initializer lists or assignment?
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 filen开发者_StackOverflow中文版ame) : _filename(filename)
{
}
}
class B
{
String _filename;
B(String filename)
{
_filename = filename;
}
}
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.
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).
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);
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.
精彩评论