In his book, Jon Skeet refers to 7 restrictions on implicit typing. I need clarification on the last two:
A. The type you want the variable to have is the compile-time type of the initialization expression.
B. The initialization expression doesn’t involve the variable being declared.
The book covers material in the same order it was released (C# 2 before C# 3). At this point C# 4 has not been introduced so I make the assumption that A does not refer to dynamic. So, when would the compile-time type be different from the execution time type of the initialization expression?
As for B, when can an initialization expression involve the variable being declared?
Regarding B, Henk gave a perfect answer (edit: it’s now removed), although I find it peculiar that
int x = x = 1;compiles. (I would’ve thought x isn’t considered declared until after the initializer. Oh, well.) His answer was:Regarding A and your question as to when the compile time type wouldn’t match the execution time type, here’s an example where they would differ:
… and that method on fooFactory is implemented as ….
Here, foo‘s type is FooBase (which may be an interface, abstract class, or unsealed concrete class), and (without casting) only its features are available. Clearly, FooSubtype implements or inherits from FooBase.
The type that foo holds at runtime can be discerned here only because I show the implementation of GetFoo(), but it isn’t inspected by the compiler. In fact, the implementation may not even be available (could be in another assembly) or it may vary (could be virtual). For determining the compile-time type of GetFoo(), and therefore of foo, only the method declaration is relevant.