3

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?

1
  • Since this uses a non-specified parameter, compare it to the how T would (or wouldn't) be inferred in T GetValue<T>() { return default(T); } .. Commented Jul 16, 2012 at 22:05

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah!.. Like in case of overloading. Interesting. Good to know. In fact replacing the usage code with the following (adding explicit default value) does eliminate a need for type specification: 'string s = SqlUtils.GetValue<string>(reader, nameOrd, "");'.
Yeah, coz now you have specified T as argument and thus not violating the rule I have cited in my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.