Help ‘Generate from usage’ help you

The C# language has generally been going in a direction where the language really helps you out in being more expressive, by spending more time writing “the meat” of your code, and less time writing boilerplate code. A couple of examples are auto-implemented properties and implicitly typed local variables.

Sometimes features like the latter are based on the ability of the compiler to infer types. So the local variable has the type of the expression you’re initializing it with in our second example.

Generate From Usage is a great feature found in Visual Studio 2010 that allows you to write first a block of code, even if you haven’t written the supporting classes and methods yet, and then use the IDE to fill those out so it builds correctly. This allows you to focus on finishing that bit of code you were originally writing, rather than having to go back and forth between the code you wanted to focus on first and the supporting types.

Now, the gotcha here is that when you write in this style, you can’t expect the compiler to help you out with type inference to then go and finish the classes for you! This doesn’t come up very often, but one example is what you get when using lambdas, whose parameter types you can usually omit because they are inferred from the delegate signature.

// No can do
instance.Callback = (stuff) => stuff.ToString();

// Much better
instance.Callback = new Func<string, string>((stuff) => stuff.ToString());

If we assume that the Callback property hasn’t been defined yet, the first line won’t allow the IDE to help you declare it – there is really no way to know what the type of “stuff” is, which is necessary to generate the right delegate type for the Callback property. On the other hand, the second line works just fine, because you’re clearly spelling it out for the compiler.

Interestingly, if the signature really bothers you in the code, you can write the code with it, generate the member, and then go back to the first form – now that the type is delclared on the Callback property, the compiler can figure out what type stuff should have.


Comments (0)

Skip to main content