0

I am trying to use a method with a parameter which is an interface with what seems like a generic type in angle brackets, but I've no idea how to pass my value into it.

The method is defined something like:

public static class Settings {

    public static void UpdateSetting<TType>(ISetting<TType> setting)
    {
        // Do its thing
    }
}

Now I try to call this by using my code such as this:

Settings.UpdateSetting<MyParticularSettingType>(new MyParticularSettingType { Value = "settingvalue"});

with, elsewhere...

public class MyParticularSettingsType : Setting<string> 

and...

public abstract class Setting<TType> : ISetting<TType>

But on the parameter, I get an error.

Cannot convert from MyNameSpace.MyParticularSettingType to SettingsNamespace.ISetting<MyNameSpace.MyParticularSettingType>

I've tried casting it, while that gets rid of the compile error, it throws an exception at run-time

Unable to cast object of type 'MyNameSpace.MyParticularSettingType' to type 'SettingsNamespace.ISetting`1[MyNameSpace.MyParticularSettingType]

Settings.UpdateSetting((ISetting<MyParticularSettingType>)(new MyParticularSettingType { Value = "settingvalue" }));

What exactly am I supposed to be doing?

komodosp
  • 3,316
  • 2
  • 30
  • 59

1 Answers1

4

Try calling the method this way.

Settings.UpdateSetting<string>(new MyParticularSettingType { Value = "settingvalue"});
danish
  • 5,550
  • 2
  • 25
  • 28
  • That did it, thanks! Also accidentally discovered that `Settings.UpdateSetting(new MyParticularSettingType { Value = "settingvalue"});` works... – komodosp May 25 '18 at 08:09
  • @colmde Yes. You might want to take a look here about this behaviour. https://stackoverflow.com/questions/4975364/c-sharp-generic-method-without-specifying-type – danish May 25 '18 at 08:26