Ashkan Mobayen Khiabani Ashkan Mobayen Khiabani - 1 year ago 92
C# Question

Passing variable type to generic method

I have a generic method :

public static T GetSetting<T>(string Key){

Which returns a setting value from database.
Now I'm trying to make it fill the class automatically with Settings:

public static T GetAllSettings<T>(this T m)
FieldInfo[] fields = typeof(T).GetFields(BindingFlags.Public);
foreach(FieldInfo f in fields)
f.SetValue(m, User.GetSetting<f.FieldType>(f.Name), null);
// ~ <=Error in here

But I'm getting the error:

'f' is a variable but is used like a type

Well I'm actually getting the
FieldType and not the

Answer Source

Since SetValue() already expects an Object as the parameter, you could simply pass object as the generic parameter of SetMethod():

f.SetValue(m, User.GetSetting<object>(f.Name), null);