user979033
user979033

Reputation: 6420

c# - Cast with GetType() and reflection

So after implemented Page Object Pattern using this tutorial i have several Pages that derived from BasePageElementMap.

And i want to handle some operation so i have this class:

public class DownloadAttachmentsHandler
    {
        public DownloadAttachmentsHandler(BasePageElementMap basePageElementMap)
        {
            Type type = basePageElementMap.GetType();            
        }
    }

Every Pages that derived from BasePageElementMap have this html elements that locate inside its class that derived from BasePageElementMap and from this Page i have this Map object that contains all my HTML elements that i am using.

public class YahooEmailPage: BasePage<YahooEmailPageElementMap, YahooEmailPageValidator>...

so in case i am call this function like this:

UploadAttachmentsHandler att = new UploadAttachmentsHandler(new YahooEmailPage().Map);

I want to cast this into YahooEmailPage from my DownloadAttachmentsHandler method.

So currently i have this type object, how can i case it into YahooEmailPage ?

Upvotes: 0

Views: 5679

Answers (1)

steliosbl
steliosbl

Reputation: 8921

If I understood correctly, you want the following:

public class DownloadAttachmentsHandler
{
    public static object Cast(object obj, Type t)
    { 
        try
        {
            var param = Expression.Parameter(obj.GetType());
            return Expression.Lambda(Expression.Convert(param, t), param)
                 .Compile().DynamicInvoke(obj);
        }
        catch (TargetInvocationException ex)
        {
             throw ex.InnerException;
        }         
    }


    public DownloadAttachmentsHandler(BasePageElementMap basePageElementMap)
    {
        Type type = basePageElementMap.GetType();
        dynamic foo = Cast(basePageElementMap, type);
    }
}

Based on this answer by balage.

EDIT: For the example, lets assume that GetType() returns the type bar. You will have to create a method like this one:

public static void UseDynamic(bar input)
{
    // Stuff
}

And then do

public DownloadAttachmentsHandler(BasePageElementMap basePageElementMap)
{
    Type type = basePageElementMap.GetType();
    dynamic foo = Cast(basePageElementMap, type);
    UseDynamic(foo);
}

You can use overloads to avoid having to write many ifs or a switch. However, whichever approach you take, you will have to create a method for each possible type.

Upvotes: 1

Related Questions