C# 'AS' equivalent for nullable types

MattP

Well-known member
Joined
Feb 29, 2008
Messages
1,206
Location
WY, USA
Programming Experience
5-10
C#'s 'as' keyword will let you do this:

VB.NET:
int? input = value as int?

Here's what I would assume the vb.net equivalent would be:

VB.NET:
Dim input As Integer? = TryCast(value, Integer?)

There's an intellisense error in the TryCast stating the operand must be a reference type but Integer? is a value type.

Intellisense on Nullable(Of Integer) says 'Represents an object whose underlying type is a value type that can also be assigned null like a reference type.'

It seems C#'s 'as' handles this like a reference type where TryCast doesn't have this built in.

In VB10 I was able to take advantage of the new CTypeDynamic function to do the casting. Conversion.CTypeDynamic Method (Microsoft.VisualBasic)

VB.NET:
Dim input As Integer? = CTypeDynamic(Of Integer?)(value)

Or:

VB.NET:
Dim input As Integer? = CTypeDynamic(Value, GetType(Integer?))

There's a cost here as CTypeDynamic examines the type at runtime.

My question is what is the elegant way to handle this without CTypeDynamic?
 
DirectCast or CType.

Nullable(Of T) is a structure, ie a value type.
 
I don't see how that is treating the value type as a reference type. You can to this:
VB.NET:
input= CType(If(value, Nothing), Integer?)
but achieve nothing over a plain DirectCast/CType.
 
Perhaps you can use a generic method like this:
VB.NET:
Public Function TryCasts(Of T)(ByVal value As Object) As T
    Try            
        Return DirectCast(value, T)
    Catch
    End Try
    Return Nothing
End Function
VB.NET:
Dim i = TryCasts(Of Integer?)(value)
 
Back
Top