Take the 2-minute tour ×

I have an object, o, and a type, T. I'd like to use reflection to change object o to type T at runtime without instantiating it.

The equivalent at compile time would be:

Dim p as Point = Nothing

I know how to use Activator.CreateInstance to create an instance at run time that is equivalent to:

Dim p as New Point()

But i don't want to do this. I have no knowledge of the type's constructor parameters and some types don't have a parameterless constructor. eg. Font.

So, to sum up, I'd like a way of performing the equivalent of:

Dim o as T = Nothing

In case you're wondering why I'm doing this, it's because I'm using a PropertyGrid on a form to edit types. If this is the first time for editing, say, a Font, then passing an uninitialised Font to the PropertyGrid makes the grid display the default values.



I tried 'o = GetUninitializedObject(T)', but the PropertyGrid either wants a properly initialised object or an object, with a defined type, set to nothing.

I've actually solved my particular problem here:


, but i'd still be interested to know how to assign a type at run-time without the use of a wrapper class (which I was lucky enough to be using).

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

The closest thing would be to set o to default(T). Assuming the default is not Nothing (null), you'll get a default value such as Rectangle.Empty or 0 (int).

Nothing (null) doesn't have a type associated with it, so if o as object, (T) Nothing won't help.

share|improve this answer
Dim o as Font = Nothing, does have the Font type associated with it. I can't use it until it's instanciated, but I can pass it to the PropertyGrid without error. Could you explain what you mean by set o to default(T). Thanks. –  Jules Jul 23 '09 at 13:33
From what I can see, setting an object to default(T) is the same in VB.Net as setting it to Nothing. –  Jules Jul 23 '09 at 14:11
With "Dim o as Font = Nothing", its the variable o that is of type Font. The nothing part is not a "no font", it's a "no object". Basically, you have to do one or the other, either the variable has the type (object doesn't work) or the value inside the variable has the type (nothing doesn't work). If you have "Nothing" in an "Object" there is no way for it to know what you meant. Using the wrapper is probably your best bet. –  Alan Jackson Jul 23 '09 at 15:24
add comment

Your Answer


