Initialization in Constructor

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
 
J

Joanna Carter [TeamB]

"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
 
G

Guest

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top