tags:

views:

92

answers:

4

Hey all,

Simply my question is about defining the type of an instance in run time, and this type is user-defined. Something which looks like this:

Type instance1;

In run time, the user is going to choose for example "int", then there 'll be,

int instance1;

Any suggestions?? is downCasting efficient here?

+2  A: 

What you are looking for are generics. Read an introduction here.

For example you would declare the class, you want that user defined type to be in, like that:

class MyClass<T>
{
    private T instance1 = default(T);

    public MyClass(T initalvalue)
    {
        instance1 = initalvalue;
    }

    //... some more code
}
Philip Daubmeier
I'm afraid, that generics is not what the OP is looking for. Shaza is talking about the end user using running application, not a programmer who uses his code. The type is supposed to be chosen at runtime
Maciej Hehl
@Maciej: that is just speculation, as long as Shaza isnt saying what he really wants to do.
Philip Daubmeier
I commented on the basic post what I'm working on and BTW, I'm a "she" :)
Shaza
@Shaza: Sorry for that. Didnt hear your name before.
Philip Daubmeier
+1  A: 

Without you explaining more details of what you are looking to accomplish, you can either use a generic method*, you can use C# 4's dynamic keyword, or you can use reflection to create instances of the given type.

*The generic method will work well if the type can be known at compile-time or if it's one of only a finite set of types, and you'll pick a type that was named at compile-time (i.e. user will say one of int, char, or double, and you'll use the correct generic accordingly). If it's completely indeterminable, you'll still need to use reflection to instantiate the generic with the type given at run time.

Mark Rushakoff
+1. Yes, I thought about solving it with generics if, like you said, there is a defined set of types known at compile time. I'm no fan of using `dynamic` if you dont interop with a dynamic language. I think its quite ugly to turn c# into something it isnt: a dynamic language.
Philip Daubmeier
A: 

dynamic Keyword in C# 4.0

M.H
A: 

I presume, this is what you are looking for:

Type myType = typeof(int);
int value = Activatior.CreateInstance(myType);

In .NET 4, the dynamic keyword is perhaps more effective and convenient.

Venemo