Tuesday, October 14 2008, 00:12
C# generics vs. code analysis
A few days ago, I published an article on heterogeneous collections in C#, proposing various possibilities to solve this problem given a specific set of constraints. My final pick was using generics, the built-in template feature of C#. But what the story did not say is that this solution triggers a code analysis warning at compile-time...
Indeed, in order to make generic methods more readable for the future code consumers, code analysis requires that these have explicit type parameters (warning CA1004). Concretely, this allows calling the method without specifying the generic type explicitly (like any other non-generic method). For example, let us consider the following "GetValue" method, without an explict type parameter:
public T GetValue<T>(string variableName);
Then, a valid call of this method is:
int value = GetValue<int>("myIntValue");
Instead, if we have an explicit type parameter in the method signature, we can omit the explicit type in the method call. Then, let us consider this other "GetValue" method:
public void GetValue<T>(string variableName, out T variable);
In this case, a valid call of this method is:
int value = 0; GetValue("myIntValue", out value);
Note that this second case works without the explicit mention of the type in the "GetValue" call. However, we have to declare the typed variable before the method call, and the method behavior is less clear than before. Even worse, this does not clean the code analysis warning list: indeed, we have now another warning (CA1021), because it is not good to have "out" parameters in a public or protected method. In other words, by trying to remove the initial warning from a good design, we reached a not as good design, which still triggers a code analysis warning.
Then, for the final word of this little story, I cannot resist the pleasure to quote Eric Lippert, senior developer from the Visual Studio managed languages team (which designed and is still designing the C# language):
Style warnings are warnings that you might be doing something bad accidentally. If you're doing it deliberately and believe the design is good, ignore the warning. Style warning tools are our servants, not our masters.