1

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 f FieldType and not the f itself

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • 1
    The type needs to be known at compile time, see http://stackoverflow.com/questions/2604743/setting-generic-type-at-runtime – PaulF Nov 28 '16 at 17:13
  • 2
    Pass `object` as the generic parameter, as `SetValue` already expects an `Object` – haim770 Nov 28 '16 at 17:13
  • Your options are either do as haim770 suggests or use reflection to call `GetSetting`. However, if you're doing this a lot, you may be better of just serialising your settings class to JSON/XML/binary and deserialising it back later. – DavidG Nov 28 '16 at 17:15
  • @haim770 Thanks a lot problem solved. no errors. Let me finish the method to see the result in action ;). I think you should add it as answer. – Ashkan Mobayen Khiabani Nov 28 '16 at 17:17
  • What does `User.GetSetting` do? It looks like you should create non-generic overloads which take a `Type` parameter and have the generic versions call those. – Lee Nov 28 '16 at 17:36

1 Answers1

1

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);
haim770
  • 48,394
  • 7
  • 105
  • 133