user107779
user107779

Reputation: 41

Working with Dynamic Types

I am using entity model with a SQL DB, and I have a set of about 30 lookup tables which are in the same 3 column format, ID, Text, IsActive. But rather than create 30 forms I would like to create one form and depending on the string name of a type given, then populate a gridview and allow ability to Insert, Update or Delete records of that type.

I have tried

string objectType = "Namespace.Models.BenefitType";
object o = Assembly.GetExecutingAssembly().CreateInstance(objectType);
Type t = o.GetType();

but I can not access the type, I get a message about it being a type of System.Type not BenefitType.

Can someone advise me on how I can cast a type that is unknown until called dynamically.

Many Thanks

Upvotes: 2

Views: 201

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

At the moment your options are limited. The framework needs to be able to know more about type information than just a string name at compile time to be able to use them easily. That means doing something like a switch statement on your type string, which isn't very nice, or making sure all your dynamic types implement some common interface you can cast to (much better).

In C# 4.0, you will be able to use the dynamic keyword to resolve these calls at runtime.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499770

I'd definitely go with an interface and then a generic type (or generic methods) rather than doing things genuinely dynamically, if you possibly can. If your autogenerated code uses partial classes, this is really easy to do - just write the interface around what you've currently got, and then add a new file with:

public partial class BenefitType : ICommonType {}
public partial class OtherType : ICommonType{} 
// etc

Then you can write:

public class LookupForm<T> : Form where T : ICommonType, new()

and you're away. The downside is that the designer isn't terribly happy with generic types.

If you need to use this based only on the type name, you can still do that:

string objectType = "Namespace.Models.BenefitType";
Type type = Type.GetType(objectType);
Type formType = typeof(LookupForm<>).MakeGenericType(type);
Form form = (Form) Activator.CreateInstance(formType);

You might want to create an abstract nongeneric form between LookupForm<T> and Form which you can use in a strongly-typed way, but which doesn't have anything to do with T. It depends on exactly what you need to do.

Upvotes: 1

Related Questions