tags:

views:

38

answers:

1

Hi!

How can I receive a string value, find an Entity with the same name and use this Entity as a type?

Thanks!!

A: 

If you have a Type in an assembly called "RipperTest.dll" and it's namespace is "RipperTest" you would put the fully qualified assembly name with as the type string.

Before using this type you have to be sure it's assembly is loaded if it's not in the calling assembly.

for a class called "Ripper1" in the RipperTest namespace in the RipperTest.dll

namespace RipperTest
{
    [Serializable]
    public class Ripper1 : RipperBase
    {
    }
}

Type myType = Type.GetType("RipperTest.Ripper1");

and then to later use this type

var newObject = Activator.CreateInstance(myType);

If your original instance implements a specific interface you can cast to that interface instead of returning an object.

like so:

var newObject = (IRipper)Activator.CreateInstance(myType);

If you're trying to return a list of classes from your current assembly you can do something like this:

Assembly execAsm = Assembly.GetExecutingAssembly();

Type myType = (from type in execAsm.GetTypes()
                                  where type.Name.Equals("YourTypeNameHere")
                                  select type).FirstOrDefault();
Michael G
I didn't understand the "Fully.Qualified.Namespace.Type"
AndreMiranda
Thanks Michael! But, just for complementing your answer, how can I make a IQueryable to retrieve data from DB for this myType?
AndreMiranda
I'm not sure I'm following you, can you post a code sample of what you're currently doing?
Michael G
For example, I've found that myType is Product (my dbml entity, right?). So using, this type that I've found, how can I make IQueryable of Product? I mean, how can I make a var x = from c in db.myType select c
AndreMiranda
Thaaaanks a lot!! :-)
AndreMiranda