What is the difference between the following code fragments?
Form1 form1 = new Form1();
and
Form1 form1;
public Class1()
{
form1 = new Form1();
}
In your specific example, there is no difference. The both will be compiled to the same IL. It is just a matter of preference / style.
In general, the difference is the following:
The first version can't access other instance members of this class, the second version can.
The difference is that you have control over exactly when the initialisation happens in the second case.
With inline initialisation, you can't rely on one to initialise another:
int a = 42;
int b = a; // not definitely known to have a value yet
When you initialise them in the constructor, you have control over the order that they run:
int a, b;
public Class1() {
a = 42;
b = a;
}
Other than that, there isn't any real difference. The inline initialisations will be placed in the constructor by the compiler, as that is the only place where such initialisation can be done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With