views:

38

answers:

3

Hi

I'm making a windows application where user selects a type from combo box. Based on the selection, using reflection I want to create instance of the respective type and invoke one of its method. The Types I want to create are also defined in the same windows app as sperate classes. But i'm getting the error as mentioned in Title. Heres my code.

Form1 code:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
        cbLogs.SelectedIndex = 0;
    }

    private void btnProcess_Click(object sender, EventArgs e)
    {
        lblMessage.Text = "";
        lblResult.Text = "";
        if (cbLogs.SelectedIndex <= 0)
        {
            lblMessage.Text = "Please select Log to be processed";
            cbLogs.Focus();
            return;
        }
        Assembly currAss = System.Reflection.Assembly.GetExecutingAssembly();
        //I get above error on below line.
        object obj = Activator.CreateInstance(currAss.FullName,"SustainabilityXpress ");
        Type type = obj.GetType();
        object result = type.InvokeMember("process", 
            BindingFlags.Default | BindingFlags.InvokeMethod,
            null, obj, null);

        lblResult.Text = result.ToString();

    }

}

ILogBase Interface:

interface ILogBase
{        
    string process();

}

SustainabilityXpress class that implements ILogBase:

public class SustainabilityXpress: ILogBase
{
    string LogName = "SUSTAINABILITYXPRESS";
    public string process()
    {
        return "Sustainabilityxpress";
    }
}
A: 

I just noticed there is a space in "SustainabilityXpress ". Try deleting it, maybe this was the issue.

Grzenio
A: 

I'm not sure if this is only in the post, but there mustn't be a space in "SustainabilityXpress ". You also have to use the full class name (including the namespace).

If this doesn't help, maybe the type simply isn't in the assembly? GetExecutingAssembly gets you the assembly where the current code is in ...

Hinek
A: 

Be sure to properly name the SustainabilityXpress class -- aren't you forgeting to prepend its namespace? (for instance, "Name.Space.SustainabilityXpress").

Also, check Activator.CreateInstance to ensure all requirements are met.

And, as @Grzenio pointed out, there may be a typo in the name SustainabilityXpress.

Humberto
thanx Humberto, adding the namespace solved my problem.
sunitw