Why var a = 7; would set a type to a certain type (i.e. int instead of byte)? Are there any rules/defaults/checks made on the fly by C# compiler?
Why var a = 7; would set a type to a certain type (i.e.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s not clear what you mean by “on the fly” – but the C# compiler simply follows the rules laid down in the spec. For a declaration of the kind:
the type of
ais the type ofexpression. The expression7is of typeint, although it’s also known to be a constant within the range ofbyte, allowing:to compile. The availability of that conversion to
bytedoesn’t change the type of the expression7though, sointis what the C# compiler uses for the type ofa.Note that I’d recommend against using
varfor constants like this. It ends up with code which can get pretty confusing around the boundaries ofint,uint,longetc.varis meant to help with anonymous types, and also to help make code more readable. When it makes code less readable, just don’t use it.