Getting Class object from its string name in C#

13,197

Solution 1

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

Solution 2

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");
Share:
13,197
Husein Behboudi Rad
Author by

Husein Behboudi Rad

Updated on June 04, 2022

Comments

  • Husein Behboudi Rad
    Husein Behboudi Rad almost 2 years

    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
    Husein Behboudi Rad almost 11 years
    Thanks for reply it is working.
  • Husein Behboudi Rad
    Husein Behboudi Rad almost 11 years
    Thanks for reply. both answer is correct and just can choose one as answer. Instead 1 upvote for clear answer.