3

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?

Husein Behboudi Rad
  • 5,434
  • 11
  • 57
  • 115
  • 2
    Try using the [Assembly Qualified Name](http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx) instead. If it's running Xamarin, it _might_ need to full qualified name. I've had the same limitations with Silverlight. – Chris Sinclair Apr 27 '13 at 11:46
  • possible duplicate of [Getting a System.Type from a type's partial name](http://stackoverflow.com/questions/179102/getting-a-system-type-from-types-partial-name) **and** [type-gettypenamespace-a-b-classname-returns-null](http://stackoverflow.com/questions/1825147/type-gettypenamespace-a-b-classname-returns-null) – nawfal Dec 05 '13 at 19:37

2 Answers2

8

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");
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
5

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

Chris Sinclair
  • 22,858
  • 3
  • 52
  • 93