Differences between variable statements in C#

Asked

Viewed 106 times

5

What is the difference between these statements:

Classex xx = new Classex();
var xx = new Classex();
Classex xx;

If in the end I can use everything in the same way (methods, properties...)

Ex.:

I create a list: List<Classex> lstx = new List<Classex>();

I add some values: lstx.Add(...)

Then I want to take some values from this list and insert in another, what is the best way to do:

var lstx_filtrada = new List<Classex>;,
List<Classex> lstx_filtrada= new List<Classex>;
List<Classex> lstx_filtrada;

2 answers

6


About the use of var or the type has explicitly already been in answered in When to use var in C#?, for this reason I think it is unnecessary to post here the first two examples.

The third option you cannot use in the same way, if you try to use the object an exception NullReferenceException will be launched because there is no instantiated object for the variable. It can only be used if further initialize the object in some way. Without a formed object any access to an instance member will fail because it has nothing to access. Note that access to class members (hence static ones) is possible because it does not depend on instance.

In C# 8 this form of declaration is prohibited, unless you keep the null object check unchecked, or declare so:

Classex? xx;

I put in the Github for future reference.

3

The difference is:

1st Case

Classex xx = new Classex();

You have created a variable xx of the kind Classex which has already been initialized with a new instance of Classex.

2nd Case

var xx = new Classex();

Same thing as before, only when you declared var you have assigned to the compiler the responsibility of 'finding out' what type of xx, as already clarified in the question and answer referenced.

Technically the two statements are the same, but one of them (the one that uses the var) is a simplified way of coding. If the variable is being created at that time and already receiving its value the compiler infers that its type will be the same type as the object it is receiving.

3rd Case

Classex xx;

As in the first, you explicitly specified the type of the variable. But in any attempt to use without a boot will result in error (in some cases including compilation), as already explained in maniero’s response.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.