I just encountered this (made up code to demonstrate the "problem"):
public ICollection<string> CreateCollection(int x)
{
ICollection<string> collection = x == 0
? new List<string>()
: new LinkedList<string>();
return collection;
}
The compiler complains:
Fehler CS0173: Der Typ des bedingten Ausdrucks kann nicht bestimmt werden, weil keine implizite Konvertierung zwischen "System.Collections.Generic.List" und "System.Collections.Generic.LinkedList" erfolgt.
Which translates roughly to:
The type of the conditional operator can not be determined, because there is no implicit conversion between List and LinkedList.
I can see why the compiler complains, but hey, come on. It is trying to play stupid. I can see that both expressions are not of the same type but have one common ancestor and as a bonus the type of the left side is also a common ancestor. I am sure the compiler can see it too. I could understand the error if the left side was declared as var
.
What am I missing here?
Edit:
I am accepting James Gaunt's explanation. Maybe Just to make it clear. I can read the compiler spec just fine. I wanted to understand why. Why did someone make the decision to write the spec that way. There must be a reason behind that design. According to James the design principle is 'no surprises'. Also CodeInChaos explains what surprises you might encounter if the compiler would try to deduce the type from common ancestors.