1
public class SettingsBase
{

}
public class SettingsDerived : SettingsBase
{

}
public class yyy
{
    public void StartUpMethod(Action<SettingsDerived> settings)
    {
        //something goes here..
        SettingsDerived ds = new SettingsDerived();
        settings(ds);//take out SettingsDerived properties..
        SettingsBase bs = Method1(settings as Action<SettingsBase>);//as operator returns null because settings is not of type Action<SettingsBase>
        //again do something on s based on extracted SettingsDerived

    }

    public SettingsBase Method1(Action<SettingsBase> settings)
    {
        SettingsBase s = new SettingsBase();
        //something goes here
        settings(s);
        return s;
    }
}

how do I achieve this? OR any work around?

techBeginner
  • 3,792
  • 11
  • 43
  • 59
  • Your code makes little to no sense without an example of its usage. Can you show the situation in which you're hoping this will work? – Simon Whitehead May 24 '13 at 04:38

1 Answers1

6

You can't, it doesn't make sense.

the settings action you pass to StartUpMethod is typed to Derived and will be entitled to use the interface of SettingsDerived. You can't then give it a base class and expect it to just handle it.

eg, if I have...

public class SettingsDerived : SettingsBase
{
   public string DerivedSetting { get; set; }
}

I'm entitled to do :-

y.StartUpMethod( a => a.DerivedSetting = "blah" );

but in the method1 you are trying to give it a SettingsBase s = new SettingsBase();

which won't have the DerivedSetting

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
  • I am using third party control(Devexpress ASP.NET MVC), whose settings goes like `SettingsBase`.. and I created a wrapper class for that control to have some additional settings which is my `SettingsDerived`.. `Method1` is nothing but I am invoking a method to get Control Settings.. and `StartUpMethod` is my wrapper class method which would invoke my wrapped control.. now could you please suggest me how do I achieve the same.. – techBeginner May 24 '13 at 05:03
  • 3
    @dotNETbeginner: Keith is right; if you have a method that takes an Apple, you can't turn it into a method that takes a Fruit; the method takes an Apple but a method that takes a Fruit could be given an Orange. You can go the other way: if you have a method that takes a Fruit then you can turn it into a method that takes an Apple, because an Apple is a Fruit. – Eric Lippert May 24 '13 at 05:51