简体   繁体   中英

C# Discover Implicit Type of variable declared with the var keyword

Say I have the following code:

var longValue = 2147483650; // Three more than the max int size
var intValue = 10;
var variableOfUnknownType = longValue - intValue;

I want to know what type variableOfUnkownType is. (ie Is variableOfUnknownType.GetType() == System.Int64 or variableOfUnkownType.GetType() == System.Int32 ?)

Of course, I could go and carefully read C# documentation on type casting in arithmetic or add a Console.WriteLine(variableOfUnknownType.GetType()); statement to my code to learn the answer to this question. However, as per C#'s var documentation

The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.

which would imply that MS Visual Studio should be able to tell me the type of the variable prior to compiling the code.

My question is: How can I use MS Visual Studio to tell me the value of this particular var variable?

只需将鼠标悬停在“ var”关键字上,它将告诉您所推断的类型

tl;dr; Answer Hover over the "var" and you see the type (Hint it is Int64/long)

Long answer: Just taking your code and replace it with the types that var represents, you get the following code:

uint longValue = 2147483650; // Three more than the max int size
int intValue = 10;
long variableOfUnknownType = longValue - intValue;

as you can see, those are three different types, but why? uint makes sense. There is no need to occupy 64 bit, if you could do the same with 32 bit and since this is a positive number we can use an unsigned integer. The int is self explanatory, however the long is a bit confusing at first.

We as programmers know that an int.MaxValue + 3 - 10 again fits in an int , but the compiler does not know that. After all, how does he know that intVariable is 10? Simple: He does not. Therefore he infers the type he knows can handle the value. Since we are subtracting here, it could lead to negative values, so he takes the signed type, which can fit the values, which is Int64/long

Btw: This was out of my head. I'd have to check integer arithmetic in c# again to completely verify this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM