cannot implicitly convert System.Type to object

Almis picture Almis · Jan 22, 2015 · Viewed 12.2k times · Source

I am trying to make the generic method for loading the form settings in .NET C# where each setting would contain it's own try catch block (to proceed with other settings when a single one is not valid). However I cannot figure out how to work around the assignment of the appsetting to an object. The comipler does not allow me to implicitly cast type of an object.

private void LoadFormSettings(object o)
{
  try
  {
    //Load settings when application is started
    Type t = o.GetType();

    // Operator '<' cannot be applied to operands of type 'method group' and 'System.Type'
    o = getAppSetting<o.GetType()>("Setting");
    // Cannot implicitly convert type 't' to 'object'
    o = getAppSetting<t>("Setting");
    // The type arguments for method... cannot be inferred from the usage. Try specifying the type arguments explicitly
    o = getAppSetting("Setting");
  }
  catch (Exception ee)
  {
  }
}

private T getAppSetting<T>(string key)
{
  string value = config.AppSettings.Settings[key].Value;
  if (typeof(T) == typeof(Point))
  {
    string[] values = value.Split(',');
    return (T) Convert.ChangeType(value, typeof(T));
  }
}

Answer

qxg picture qxg · Jan 22, 2015

Type is type and t is an instance. Generic requires type instead of instance. You can only write F<Type>() instead of F<t>(). In your case it's better write

Type t = o.GetType();
o = getAppSetting("Setting", t);

object getAppSetting(string key, Type t)
{
  string value = config.AppSettings.Settings[key].Value;
  if (t == typeof(Point))
  {
    string[] values = value.Split(',');
    return Convert.ChangeType(value, t);
  }
}