Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 filename) : _filename(filename)     {     } } 


class B {     String _filename;      B(String filename)     {         _filename = filename;     } } 
like image 343
mindless.panda Avatar asked Mar 12 '10 19:03

mindless.panda


People also ask

What is initialization in C?

Initialization is the process of locating and using the defined values for variable data that is used by a computer program. For example, an operating system or application program is installed with default or user-specified values that determine certain aspects of how the system or program is to function.

What happens when you initialize a variable in C?

Static Initialization: Here, the variable is assigned a value in advance. This variable then acts as a constant. Dynamic Initialization: Here, the variable is assigned a value at the run time. The value of this variable can be altered every time the program is being run.

What is initialization in C with example?

Initialization of Variablevariable_name=constant/literal/expression; Example: int a=10; int a=b+c; a=10; a=b+c; Multiple variables can be initialized in a single statement by single value, for example, a=b=c=d=e=10; NOTE: C variables must be declared before they are used in the c program.

Does C initialize variables to 0?

In C programming language, the variables should be declared before a value is assigned to it. In an array, if fewer elements are used than the specified size of the array, then the remaining elements will be set by default to 0.


1 Answers

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.

like image 68
JaredPar Avatar answered Sep 19 '22 19:09

JaredPar