Reputation: 4092
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;
}
}
Upvotes: 32
Views: 57279
Reputation: 16687
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);
Upvotes: 12
Reputation: 311
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.
Upvotes: 1
Reputation: 5293
Did you mean C++ instead of C#?
For C++, initializer lists are better than assignment for a couple of reasons:
Upvotes: 19
Reputation: 754763
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.
Upvotes: 99