Initialization in Constructor

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi folks,

In C++ I was able to initialize variables in the constructor like so -

private int a, b, c;

public myClass() : a(0), b(0), c(0)
{

}

Is this possible in C#? Tried it and it didnt seem to work.

Thanks,
David
 
"David++" <[email protected]> a écrit dans le message de (e-mail address removed)...

| In C++ I was able to initialize variables in the constructor like so -
|
| private int a, b, c;
|
| public myClass() : a(0), b(0), c(0)
| {
|
| }
|
| Is this possible in C#? Tried it and it didnt seem to work.

Nope, but you can initialise fields in the declaration. Also remember that
all fields are initialised to their "0" value by the constructor anyway, so
ints will always be 0, strings will always be null, etc.

But if you need explicit initialisation to the non-default value, then you
can do this :

public class MyClass
{
private int a = 1;
private int b = 2;
private int c = 3;

public MyClass()
{
//
}
}

Joanna
 
Joanna Carter said:
"David++" <[email protected]> a écrit dans le message de (e-mail address removed)...

| In C++ I was able to initialize variables in the constructor like so -
|
| private int a, b, c;
|
| public myClass() : a(0), b(0), c(0)
| {
|
| }
|
| Is this possible in C#? Tried it and it didnt seem to work.

Nope, but you can initialise fields in the declaration. Also remember that
all fields are initialised to their "0" value by the constructor anyway, so
ints will always be 0, strings will always be null, etc.

But if you need explicit initialisation to the non-default value, then you
can do this :

public class MyClass
{
private int a = 1;
private int b = 2;
private int c = 3;

public MyClass()
{
//
}
}

Joanna

Excellent, that helped a lot. Thanks very much ;-)

David
 
Back
Top