I have a simple method:
public static T GetValue<T>(SqlDataReader reader, int columnIndex, T defaultValue = default(T))
{
return reader.IsDBNull(columnIndex) ? defaultValue : (T)reader[columnIndex];
}
and usage of it:
string s = SqlUtils.GetValue<string>(reader, nameOrd);
I asked myself, why do I have to specify <string> if it’s clear from usage that type of the returned parameter is string? But apparently I have to because otherwise compiler complains The type arguments cannot be inferred from the usage.... Where is my logic fails?
Nowhere. According to the specification (
25.6.4 Inference of Type Arguments) the compiler does generic type inference only using arguments, not return values (I remind you that you have omitted the default value parameter in your method call and thus violating this rule). So if you want to use C#, the specification simply tells you that generic type inference is not possible with return types only. Or simply use some other CLS language which allows this. C# doesn’t.