One of my data types in SqlServer is smallint and this maps to short or Int16 in .NET. I was using a simple for loop with i being an int and it told me it couldn’t implicitly convert between the two?
I was just wondering why this isn’t possible? Is it just to prevent you from using a larger number than a short can hold? It seems strange to me because I’m around 80% sure I’ve never had to convert an int to a long?
Sample:
public Int16 Test()
{
int i = 2;
return i;
}
An implicit from
shorttointshould exist because you are going from narrow to wide, wide to narrow is not supported implicitly because of potential data loss. The compiler allows you to ignore this, but requests that you cast explicitly in these cases to state that you’ve understood the potential and that you are OK with it.Update:
Your code is a narrowing cast and cannot be done implicitly. Fix:
Although, to be facetious, in this particular case the compiler could theoretically know that no data loss will occur. For the other 99.99% of the time it cannot know this at compile time, thus only explicit casting is supported where data loss might occur.
This clearly places the onus on the developer such that when a runtime error occurs due to data loss, the developer would have had to consciously make that decision prior and has no legal standing to hurl expletives at the computer.
VB.NET appears to allow you to circumvent even this restriction using Option Strict:
http://msdn.microsoft.com/en-us/library/k1e94s7e(v=vs.80).aspx
So I presume this is a C# specific design choice.