Emirhan Özlen
Emirhan Özlen

Reputation: 484

Obtaining an object's type in an extension method on compile-time for generic type usage

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.

Upvotes: 1

Views: 47

Answers (1)

Emirhan &#214;zlen
Emirhan &#214;zlen

Reputation: 484

I solved this with introducing a middle struct, structure to casting:

public static Downcasting<TParent> Downcast<TParent>(this TParent parent) {

    return new Downcasting<TParent>(parent);
}

public struct Downcasting<TParent> {

    private readonly TParent parent;

    public Downcasting(TParent parent) { this.parent = parent; }

    public TChild To<TChild>() {

        var config = new MapperConfiguration(c => c.CreateMap<TParent, TChild>());
        var mapper = config.CreateMapper();

        return mapper.Map<TChild>(parent);
    }
}

This way I can make use of:

 var parent = new Parent{ Name = "Bob" };
 var child = parent.Downcast().To<Child>();
 ...
 Assert.AreEqual(parent.Name, child.Name);

However I'm still curious about for other possible solutions.

Upvotes: 1

Related Questions