I have the following extension method in order for down-casting, mapping parent's properties to child with AutoMapper
using AutoMapper; /**/
public static TChild Downcast<TChild, TParent>(this TParent parent) {
var config = new MapperConfiguration(c => c.CreateMap<TParent, TChild>());
var mapper = config.CreateMapper();
return mapper.Map<TChild>(parent);
}
It works pretty well as expected (sample usage):
var parent = new Parent{ Name = "Bob" };
var child = parent.Downcast<Child, Parent>();
...
Assert.AreEqual(parent.Name, child.Name);
What I'm curious about is, I feel like there should be some way to actually have information about the compile time type of parent, without supplying it, after all, the class is where I call from, and it is-(should be) known at compile time.
So are there any way that I'd simplify this into something such:
public static TChild Downcast<TChild>(this TParent parent) where TParent : caller {
var config = new MapperConfiguration(c => c.CreateMap<TParent, TChild>());
var mapper = config.CreateMapper();
return mapper.Map<TChild>(parent);
}
And use it such:
var child = parent.Downcast<Child>();
Thank you for your time.