What is the difference between the following code fragments?
Form1 form1 = new Form1();
and
Form1 form1;
public Class1()
{
form1 = new Form1();
}
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.
in the first one, you are simply initializing the variable in the class, and in the second, you are initializing the variable inside the constructor.
There is hardly any performance tradeoff in both of them. Apart from the semantic easiness, its your choice, with what you go ahead.
Read it more here
In the second option you declare a reference of type Form1
which does not include anything (no object) until you inialize it by using the new
Keyword in the constructor. In the first option you declare and initialize at once.
The result of the first fragment is that form1 will contain a new instance of the class Form1.
The second fragment does not create a new instance, only an uninitialized variable (well it will be initialized to null).
Combined it would be:
Form1 form1;
public Class1()
{
form1 = new Form1();
}
Now the code fragement above is part of a class, when you create an instance of such a class it will call Class1, resulting in form1 being assigned to a new instance of Form1. E.g.:
class Class1
{
Form1 form1;
public Class1()
{
form1 = new Form1();
}
}
c = Class1();
c will call the constructor of Class1, which calls new Form1() and assigned it to form1.
According to The C# Specific Language Specification 10.11.3:
Variable initializers are transformed into assignment statements, and these assignment statements are executed before the invocation of the base class instance constructor. This ordering ensures that all instance fields are initialized by their variable initializers before any statements that have access to that instance are executed.
In your specific example, there is no example. However, if we run an example in this specification here :
using System;
class A {
int x = 1;
int y;
public A() {
y = -1;
}
}
When new A() was invoked the out put of x = 1 and y = 0 (default value) until constructor was executed.