It sounds like you have problem with some programming concepts you still have to understand; and the particular issue you faced with is
typing, which is one of the basics. Is so, this should understand what you are missing:
https://en.wikipedia.org/wiki/Type_system#Strong_and_weak_typing[
^].
Note, that that reading the articles like this one won't really teach typing or using programming language, it just define the field of knowledge you need to be aware of. Programming itself needs to be learned by learning one or more programming languages and doing software development. In particular, C# and .NET typing
paradigm combined different approaches, but primary paradigms are
static,
strong,
safe and
nominative, others should better be considered as supplementary:
https://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29[
^].
In particular,
var
is not a primary expressive device of the language, is not a type, is not always applicable and is related to
type inference
https://en.wikipedia.org/wiki/Type_inference[
^],
https://msdn.microsoft.com/en-us/library/dd233180.aspx[
^].
In other words, the code using
var
is strictly equivalent to the code with explicit type declaration which you can substitute after type inference is performed
statically.
Your first code sample makes no sense because
testa
is not defined. And everywhere,
if (true)
is just weird, as it is equivalent to not having any "if" at all. In second sample, you are doing bad thing,
typecast, which has nothing to do with variable declaration. It truncates 2.5 to 2. It makes no sense, because if you really wanted 2, you should declare
const int a = 2
. (Don't forget
const
.) It all makes no sense. You need to declare what you want and control your type, instead of getting surprised that something goes out of your control.
—SA