views:

77

answers:

2

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

A: 

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.

Joel Coehoorn
Thanks for the advice Joel
+1  A: 

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.

Jon Skeet
Thanks Jon, I'll try and work this through