Click here to Skip to main content
12,292,006 members (75,270 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

4.4K views
5 bookmarked
Posted

Changing Type

, 15 Feb 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
Sometimes you need to change objects type to another type.Convert.ChangeType does this job for you. But when you use Nullable(Of T), this function throws an exception.You can use the following function to change type(including Nullable types) safely... Private Function CType2(ByVal...
Sometimes you need to change objects type to another type.Convert.ChangeType does this job for you. But when you use Nullable(Of T), this function throws an exception.
You can use the following function to change type(including Nullable types) safely...

Private Function CType2(ByVal refObject As Object, ByVal destType As System.Type) As Object
    If destType Is Nothing Then Throw New ArgumentException("Destination Type is null")
    If refObject.GetType() Is destType Then Return refObject
    If destType.IsGenericType And destType.GetGenericTypeDefinition().Equals(GetType(Nullable(Of ))) Then
        If refObject Is Nothing Then Return Nothing
        Dim c As New System.ComponentModel.NullableConverter(destType)
        destType = c.UnderlyingType
    End If
    Return Convert.ChangeType(refObject, destType)
End Function

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

yozi
Software Developer (Senior) Adasoft
Turkey Turkey
I'm a software developer at Adasoft.
My specialists is on Web and Silverlight.

Especially i like wroting javascript codes(It is much harder,but gets more satisfaction Smile | :) )

You can reach my tips at my homepage(Turkish only)

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160518.1 | Last Updated 16 Feb 2010
Article Copyright 2009 by yozi
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid