New object from type? Specifically a resx file. I want a different resx at runtime

520 views Asked by At

I'm trying to use browser specific resx files in some automation tests. I'm stuck at the point where I wish to instansiate the type. Can anyone point me in the right direction? I have tried activator.createInstance etc... with no luck.

 public class WebAiiBaseTest : BaseTest
{
    private readonly IDictionary<BrowserType, Type> resxMapper = new Dictionary<BrowserType, Type>{
                                                                {BrowserType.Chrome, typeof(Chrome)}
                                                                , {BrowserType.Safari, typeof(Safari)}
                                                                , {BrowserType.FireFox, typeof(Firefox)}
                                                                , {BrowserType.InternetExplorer, typeof(InternetExplorer)}
                                                            };



    [TestFixtureSetUp]
    public void FixtureSetup()
    {
        Initialize();
        Launcher.LaunchRepairInformation();

    }

    [TearDown]
    public void TestCleanUp()
    {
        Launcher.NavigateToRepairInformation();
    }

    [TestFixtureTearDown]
    public void FixtureCleanup()
    {
        CleanUp();
    }

    protected object BrowserResx
    {
        get { return Activator.CreateInstance(resxMapper[ActiveBrowser.BrowserType]); }

    } 


}

This code returns an instance, but it is of type object. I would like to return a strongly typed instance. I have tried the generic overload for CreateInstance, like this

return Activator.CreateInstance<resxMapper[ActiveBrowser.BrowserType]>(); 

but Visual Studio does not like this syntax. What am I doing wrong here? Thanks for any tips or advice.

Cheers,
~ck in San Diego

2

There are 2 answers

2
Davita On

your code is not correctly spelled, did you try

return Activator.CreateInstance(resxMapper[ActiveBrowser.BrowserType]); ?

0
Jamie Treworgy On

I'm still not getting exactly what you're trying to do but here are the only things I can think of, I'm not sure the comment thread is getting any more clear.

public interface IBrowser
{
}
public class Chrome: IBrowser
{
}
... 

protected IBrowser BrowserResx
{
    get { return (IBrowser)Activator.CreateInstance(resxMapper[ActiveBrowser.BrowserType]); }

} 

Alternatively:

protected T BrowserResx<T> where T: IBrowser
{
        get { return (T)Activator.CreateInstance(resxMapper[ActiveBrowser.BrowserType]); }
}

.. if your class was designed as a generic. If there's no base class for the browser types, or interface, then there's no way to return something more strongly typed: they only share "object" in common.