HischT
HischT

Reputation: 953

Create objects dynamically when knowing part of classname in C#

I am using an external DLL which has an abstract baseclass Packet and subclasses to Packet.

The subclasses are named after the number they represent, one name could be P132_RandomString. I am parsing a file containing these numbers and for each number I want to create a corresponding object. There are hundreds of different subclasses and the DLL have no factory method (at least not for my input).

The problem is I don't know the "RandomString" part, if I did I could have used Reflection but I assume there is no way to use Reflection since I only know the beginning of the classname?

The only solution I could think of is implementing my own factory method with hundreds of case statements but this feels a bit cumbersome...

My question is: is there a nice way to do this?

Upvotes: 1

Views: 270

Answers (4)

James
James

Reputation: 2463

You can use a LINQ Where clause to grab the type you want. Consider the following program: (This assumes you know the base class and the prefix)

class Program {
    static void Main( string[] args ) {

        string prefix = "p22";
        IEnumerable<Type> types = Assembly.LoadFrom("c:\\Sample.Assembly.dll").GetTypes();    
        Type baseClass = typeof(foo);
        Type foundType = types.Where(
            t => t.Name.StartsWith( prefix ) &&
                t.IsSubclassOf( baseClass )
                ).SingleOrDefault();
        foo myClass = (foo)Activator.CreateInstance( foundType );
                //Do Stuff with myClass 
    }
}
abstract class foo { }
class p22_notMyClass { }
class p22_myclass : foo { }
}

Upvotes: 2

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

Use Assembly.GetTypes + some String.IndexOf (or other matching) on Type.FullName + Activator.CreateInstance().

Upvotes: 0

Amiram Korach
Amiram Korach

Reputation: 13286

you can use Assembly.GetTypes() method and iterate the types and find out which class has the number in its name. Then you can use Activator.CreateInstance to get an instance.

Upvotes: 0

Ivan Manzhos
Ivan Manzhos

Reputation: 743

To load all types from assembly use Assembly.GetTypes

 var objects = new List<Object>();
 Assembly SampleAssembly;
 SampleAssembly = Assembly.LoadFrom("c:\\Sample.Assembly.dll");
 // Obtain a reference to types known to exist in assembly.
 Type[] types = SampleAssembly.GetTypes();
 foreach(Type t in types)
    if(t.Name.StartsWith("P132")
       objects.Add(Activator.CreateInstance(t));

Use Activator.CreateInstance method described here

Upvotes: 0

Related Questions