Jules
Jules

Reputation: 4339

Assign a type to an object at runtime in vb.net or c#

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.

Cheers.

ETA:

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:

how-to-use-the-property-grid-in-a-form-to-edit-any-type

, 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).

Upvotes: 0

Views: 2260

Answers (1)

Alan Jackson
Alan Jackson

Reputation: 6511

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.

Upvotes: 2

Related Questions