MightyMouseTheSecond
MightyMouseTheSecond

Reputation: 99

Cast Action<T1> to Action<T2> in c# where T1 and T2 have no relation

I've got two objects which (Domain and Data) which in this case have the same property (let's presume Name). I've got an Action<DomItem> which I would like to cast to Action<DataItem>.

public  class DomItem {
    public string Name { get; set; }
}

public class DataItem {
    public string Name { get; set; }
}

public class Program {
    public Program() {
        Action<DomItem> domAction = new Action<DomItem>(x=>x.Name = "Test");
        // Something Casted To Action<DataItem>(x=>x.Name = "Test");
    }
}

Of course this is just a basic example. It's by design that I can NOT use a common interface. I do not care about the DataItem might not be having the same property.

I've been looking into Expressions and several other solutions but I just can't figure out how to create the Cast (or get the "x=>x.Name =..." part from the method).

Any help would be really appreciated!

Upvotes: 1

Views: 391

Answers (1)

D Stanley
D Stanley

Reputation: 152491

You can't directly or indirectly cast a Action<DomItem> to an Action<DataItem>, but you could wrap the action with a converter that converts the input from a DataItem to a DomItem and runs the original action on the copy:

public Action<DataItem> Convert(Action<DomItem> action)
{
    return new Action<DataItem>(o => action(Map(o)));
}

public DomItem Map(DataItem dataItem)
{
    return new DomItem{Name = dataItem.Name};
}

The obvious downside is that the action will be applied to a copy of the original object and not the original object itself. Without knowing exactly what the action is I don't know of a way to "cast" the action without a common base type.

Upvotes: 2

Related Questions