Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Class object from its string name in C# [duplicate]

I'm using C# for developing mobile applications(Monotouch, monodroid). I have a class by this definition:

public class TempIOAddOn : BaseIOAddOn 
{
    public TempIOAddOn ()
    {
    }
}

And I use this code to access an instance of class by its string name:

BaseIOAddOn tempIOAddOn;
            Type t= Type.GetType("TempIOAddOn" );
            tempIOAddOn  = (BaseIOAddOn)Activator.CreateInstance(t);

But after executation, t is null.

I tried below code also:

BaseIOAddOn tempIOAddOn;
            tempIOAddOn = (BaseIOAddOn )System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("TempIOAddOn" );

But again I face with null. tempIOAddOn is null.

What is wrong with me?

like image 1000
Husein Behboudi Rad Avatar asked Jun 17 '26 09:06

Husein Behboudi Rad


2 Answers

Your class is almost certainly included in a namespace. In this case you need to qualify the name of the type with its namespace:

Type t= Type.GetType("MyNamespace.TempIOAddOn");
like image 187
Sergey Kalinichenko Avatar answered Jun 19 '26 00:06

Sergey Kalinichenko


Try using the Assembly Qualified Name instead. If it's running Xamarin, it might need to use the full qualified name. I've had the same limitations with Silverlight.

To quickly get the full name, just reference the type and output it:

Console.WriteLine(typeof(TempIOAddon).AssemblyQualifiedName);

EDIT: Here's the MSDN doc for Type.GetType(string) for Silverlight. Since Xamarin's mobile platform is more or less based off it, generally the docs can apply: http://msdn.microsoft.com/en-us/library/w3f99sx1%28v=vs.95%29.aspx

Note that likely if the type is in the currently executing assembly, you'll probably only need the full namespace.name

like image 29
Chris Sinclair Avatar answered Jun 18 '26 23:06

Chris Sinclair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!