In C #, how are variables using var derived in terms of memory and life cycle?

Ok, I read everything that I can find on var, and I'm sure I have a pen on their basic behaviors and type of output. I've always been a big proponent of explicit types, so var annoys me a bit when I read the code. Therefore, I have a couple of questions regarding the use of memory and the behavior of a variable declared with var during the life cycle of this variable in memory.

Since var is the output for an explicit or anonymous type, whether its memory would be allocated in the same place that its corresponding type would be or would be universal, created on the heap and accessible as if it were an object. As an example:

int i = 5;  // puts this on the stack
var i = 5;  // does this also go on the stack?

Is the declared var a constant type after it is initialized, or can it be adjusted? I ask about this because I cannot find in the documentation that indicates this, and I just read something in this SO @Eric Lippert question :

a variable is a storage location, content change

By testing the following code, I see an implicit conversion exception even at the IDE level. At this point, I have no experience with LINQ to perform a similar test with respect to anonymous types. Do they follow the same behavior? Will the IDE recognize type mismatch at design time, or will such code receive an exception at run time?

var i = 5;    // Initializes as int, value is 5
i = "Steve";  // Type casting error

, - , , , var ? , , , , , .

EDIT: , , , ( ). , , , , .

+3
5

var - 100% #. , . var -declared , . , , , var , . :

var i = 10;
int j = 10;

( , var int, , ).

+17

var , , :

var i =0;

int i = 0;

.

,

var MyVar = new { prop1="A string", prop2=5};

var varables , . :

var MyVar = new { prop1="A string", prop2=5};
MyVar = "Fred";
+9

, var , - , . , -, , -, "" - #. ( <>, .)

, var, . , , , var... , "" , int, , int.

, var, , :

  • , , , ,
  • , var
  • var , , ,
  • var, - .

: var, . , . , , ... , , , , . note, # , .

+4

: , .

var () . var - . , , var .

+3

" var , , , , "

var , var , :

var number = 1;

:

System.Int32 number = 1;

... . . var - . , , .

var, , :

var i = 5;
i = "Steve"; 

... , Int32.

, .

", - , , , var ?"

:

:

int i = 5;
string name = "Matt";

:

var instance = new MyComplexTypeInstance();

For LINQ results, I stick with var:

var result = from i in something select i;

For methods, if the method describes a handle to the return type, I will use var.

var instance = GetInstance();

While more complex method names, I would put the actual type:

Result result = DoSomethingWeirdAndWonderful(); 

Each developer will find what is convenient for them, the choice is yours. Since var is really a thing of development time, all its syntactic sugar.

+1
source

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


All Articles