How does the C # compiler interpret objects specified by the var keyword?

How does the C # compiler interpret objects specified by the var keyword? When should we use this keyword?

+3
source share
4 answers

In the Var declaration,

The compiler infers the type from the assigned value.

on

var a = 100;     // compiler assumes a is a integer
var b = "test";  // compiler assumes b is a string

Why do we need them (why can't we use objects directly)

Because the object does not provide type security

  object objtest = 1;
  objtest = "test";

it works great.

But var provides type safety

  var a = 100;    
  a= "test";  

this does not compile and will give a compile-time error.

Where can we use them

  • Linq queries returning anonymous types
  • , (). - .

.

   RootClass rt = new RootClass ();
   List<RootClass > rt = new List<RootClass >();

var aaaaaa = new RootClass ();
var ls = new List<RootClass>();
+2

var, , , , LINQ:

var results = context.People.Select(p => new {p.PersonID, p.Name});

{} ? , . , , , - "var". LINQ.

, var , - . . , , :

var i = 12;
i = i + "foo!";

.

+6

var ( #)

Visual # 3.0, , , var. , , .

+4

"var", , , "var type". "var" ( ) , , .

+1

Source: https://habr.com/ru/post/1733340/


All Articles