tags:

views:

248

answers:

2

In the code base I'm working in there have a method that has the signature

Public Sub SetDropDownValue(Of T As Structure)(ByVal target As ListControl, ByVal value As Nullable(Of T))

The method I am writing is passed a parameter of type object.

How can I cast the object into something that can be passed into the SetDropDownValue method?

A: 

No, you won't be able to cast a reference type as a value type (which is what the Structure constraint signified). The CLR does allow you to cast a value type as a reference type (this is known as boxing) but the nature of the difference between the implementation (and semantics) of these two different types makes the reverse impossible.

The only think you could do would be to create a value type that held a reference to your object as a field, but perhaps this problem may be a hint that you are going about the whole thing in the wrong way.

Andrew Hare
I was starting to think the code was getting a bit smelly. Time to rethink.
ilivewithian
A: 

This should work if you know T:

something.SetDropDownValue(target, DirectCast(value, Nullable(Of T)))

See this article for details.

If you don't know the type T, you're in trouble and would have to start futzing around with reflection at runtime. This is complex, dangerous, and has awful performance.

David Schmitt