Differences between declarations of variables in C #

5

What's the difference between these statements:

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

If at 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 get some values from this list and insert it into another one, which is the best way to do it:

var lstx_filtrada = new List<Classex>;,
List<Classex> lstx_filtrada= new List<Classex>;
List<Classex> lstx_filtrada;
    
asked by anonymous 29.05.2018 / 22:16

2 answers

6

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

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

This form of declaration will be banned in C # 8, unless you keep the null object check off, or declare it as follows:

Classex? xx;
    
29.05.2018 / 22:18
3

The difference is:

1st Case

  

Classx xx = new Classx ();

You have created a xx variable of type Classex that has already been initialized with a new instance of Classex .

2nd Case

  

var xx = new Classex ();

Same thing as above, except that when you declared var you assigned the compiler the responsibility of 'discovering' what type of xx , as already explained in question and answer referenced .

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

3rd Case

  

Classex xx;

As in the first, you explicitly specified the type of the variable. But any attempt to use without a boot will result in an error (in some cases of compilation inclusive), as already explained in the Maniero .

    
29.05.2018 / 22:54