So let's say I have a type X
which is an abstract class, like so public abstract class X
. Now let's say i have a type A
which derives from type Y
, like this public class A : Y
. Both X
and Y
have the same definition:
public abstract class X
{
public string Name { get; internal set; }
public virtual void PrintName()
{
Console.WriteLine(Name);
}
}
public abstract class Y
{
public string Name { get; internal set; }
public virtual void PrintName()
{
Console.WriteLine(Name);
}
}
I can't change anything inside X
(Add interface, ...). Also I can not derive from X
because a program would automatically load it. The classes X
and Y
are bigger with fields, properties and a load of methods, but I kept it as minimal, as possible. Is it possible to convert A
into X
? Something like
X obj = (X)(new A())
I have already tried: Json De/Seriliazation, using dynamic X cls = (X)(new A() as dynamic);
. I probably could use a TypeBuilder, but I don't have any experience using TypeBuilder.
I think you could solve this problem by using AutoMapper: https://docs.automapper.org/en/stable/Mapping-inheritance.html
After adding the AutoMapper nuget package to your project, add the following class:
public class XYBAProfile : AutoMapper.Profile
{
public XYBAProfile()
{
CreateMap<Y, X>()
.Include<A, B>();
CreateMap<A, B>();
}
}
Now you should be able to create the X object from any A object:
public static void Test()
{
var mapperConfig = new AutoMapper.MapperConfiguration(conf => conf.AddProfile<XYBAProfile>());
var mapper = mapperConfig.CreateMapper();
var a = new A() { Name = "Something" };
X x = mapper.Map<X>(a);
x.PrintName();
}