Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring instances differences [duplicate]

Tags:

c#

winforms

What is the difference between the following code fragments?

Form1 form1 = new Form1();

and

Form1 form1;

public Class1()
{
    form1 = new Form1();
}
like image 994
Etrit Avatar asked May 25 '26 03:05

Etrit


2 Answers

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.

like image 165
Daniel Hilgarth Avatar answered May 26 '26 16:05

Daniel Hilgarth


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.

like image 36
Guffa Avatar answered May 26 '26 16:05

Guffa