C # is a strongly typed language in which variables must be declared type before they can be used, and the use of variables needs to be fully defined. That is, once a variable is assigned a data type, it is always the data type if it is not converted by type. In contrast, weakly typed languages are languages that data types can ignore, and a variable can give values of different data types.
C # supports implicit type conversions:
1 Static void Main (string[] args)2{3short 6; 4 int b = A; 5 }
But the following code:
1 Static void Main (string[] args)2{3 int6; 4 Short B = A; 5 }
"Error 1 cannot implicitly convert type" int "to" short ". An explicit conversion exists (is there a missing cast?) ”。
converting int to short is dangerous, so C # does not encourage programmers to do so.
If you must write this, you can change to an explicit type conversion:
1 Static void Main (string[] args)2{3 int6; 4 Short B = (short) A; 5 }
As a programmer, however, you should be aware of the problems that this statement may cause.
Next look at a program like this:
1 Static void Main (string[] args)2{3short 0xffff; 4 Console.WriteLine (a); 5 }
What we're going to do is assign 0xFFFF (-1) to the short variant A, which seems to have no problem, but the compiler hints:
Error 1 constant value "65535" cannot be converted to "short"
The reason is that hexadecimal constants in C # are by default int, and assigning a direct value to a short type of variable is obviously not feasible.
So what if we add an explicit type conversion to it?
1 Static void Main (string[] args)2{3short a = (short ) 0xFFFF; 4 Console.WriteLine (a); 5 }
The compilation is still, but the error message has changed:
Error 1 constant value "65535" cannot be converted to "short" (rewritten with "unchecked" syntax)
It seems that the compiler still does not allow us to do so, try unchecked rewrite:
1 Static void Main (string[] args)2{3 unchecked4 { 5 Short a = (short)0xffff; 6 Console.WriteLine (a); 7 }8 }
Find out at last!
Unchecked syntax: an overflow check used to cancel integer arithmetic operations and conversions.
It was then found that C # had very strict checks on the overflow, such as int a = 2147483647 * 2; and int a = 2147483647 + 1; The statement normally cannot be compiled, and 2147483647 is the maximum value that int can represent.
and the existence of the unchecked grammar makes these statements can be executed, the heart suddenly feel that C # this language is very miscellaneous (support super-many keywords and syntax), but many features are very practical.
C # Learning about the possible problems caused by the assignment of a third projectile to a constant value