tags:

views:

37

answers:

2

Can't imagine this isn't a dupe but I can't seem find any previously matching questions.

I have a generic method

public T GetSetting<T>(Guid userId) where T : ISetting, new()

This in it's turn calls a generic method

public static ISetting CreateSetting<T>(IDictionary<string, object> data) where T:ISetting, new()

The signatures of T are exactly the same, yet the compiler requires me to cast the value like so:

return (T) BaseSetting.CreateSetting<T>(data);

Am I doing something wrong, or is this just a limitation of the framework?

+2  A: 

The method is returning the type ISetting. While a T reference is always an ISetting reference, an ISetting reference doesn't have to be a T reference. That is why you have to cast it.

Guffa
Correct :) Thanks
borisCallens
+1  A: 

The signature of CreateSetting only states that it returns an ISetting. It doesn't require that that ISetting has to be of type T.

If you change the signature to

public static T CreateSetting<T>(IDictionary<string, object> data) where T:ISetting, new()

it will work without casting.

sepp2k