473,387 Members | 3,781 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Problem: InvalidCastException When Casting Object As Generic Type

I have written a Generic method that takes an object, a type, T, and returns
a System.Nullable (Of T) depending on whether or not the object IsDBNull.

It was working fine until I tried to pass a string as the object and my own
custom Structure as the type, T. Then I received an InvalidCastException.
This is despite the fact that a CType from a String to my Structure works
fine. I assume I probably need to implement some interface that
VisualBasic.CompilerServices.Conversions.ToGeneric Parameter can call. But I
don't know what that interface might be.

I have narrowed everything down here to reproduce the error I am
experiencing. Please note that this code is simplified and doesn't do the
DBNull checking or the conversion to a System.Nullable(Of T). If the code
below can be solved, I can work on fixing the more complex code I actually
have.

Here is the code to reproduce the error. Just drop into a console application:

' no error checking right now, just plain jane simple
Public Structure FancyInt

Public Value As Integer

Public Overloads Shared Narrowing Operator CType(ByVal source As String) As
FancyInt
Dim fi As FancyInt
fi.Value = CInt(source)
Return fi
End Operator

Public Overloads Shared Widening Operator CType(ByVal source As FancyInt)
As String
Return source.ToString
End Operator

Public Overrides Function ToString() As String
Return Value.ToString
End Function

Sub New(ByVal s As String)
Value = CInt(s)
End Sub

End Structure

Module Module1

Sub Main()
Console.WriteLine(New FancyInt("061091977")) 'good
Console.WriteLine(CType("061091977", Integer)) 'good
Console.WriteLine(CType("061091977", FancyInt)) 'good
Console.WriteLine(FancyConvert(Of Integer)("061091977"))' good
Console.WriteLine(FancyConvert(Of FancyInt)("061091977")) 'bad line 18
End Sub

Function FancyConvert(Of T As Structure)(ByVal o As Object) As T
Return CType(o, T) ' line 21
End Function

End Module

Here is the console output of the above Sub Main:

C:\>Test.exe

61091977
61091977
61091977
61091977
System.InvalidCastException: Specified cast is not valid.
at
Microsoft.VisualBasic.CompilerServices.Conversions .ToGenericParameter[T](Object Value)
at Test.Module1.FancyConvert[T](Object o) in
C:\TestProject\Module1.vb:line 21
at Test.Module1.Main() in C:\TestProject\Module1.vb:line 18

C:\>

So, what do I need to do to FancyInt so it is successfully cast just like
the Integer is successfully cast?

FYI - I also already tried implementing IConvertible on FancyInt as well as
tried implementing a TypeConverter along with applyng the TypeConverter
attribute on FancyInt, but no luck with either.

I must be missing something simple.

Any help?
Aug 24 '07 #1
1 2216


BJS wrote:
I have written a Generic method that takes an object, a type, T, and returns
a System.Nullable (Of T) depending on whether or not the object IsDBNull.

It was working fine until I tried to pass a string as the object and my own
custom Structure as the type, T. Then I received an InvalidCastException.
This is despite the fact that a CType from a String to my Structure works
fine. I assume I probably need to implement some interface that
VisualBasic.CompilerServices.Conversions.ToGeneric Parameter can call. But I
don't know what that interface might be.

I have narrowed everything down here to reproduce the error I am
experiencing. Please note that this code is simplified and doesn't do the
DBNull checking or the conversion to a System.Nullable(Of T). If the code
below can be solved, I can work on fixing the more complex code I actually
have.

Here is the code to reproduce the error. Just drop into a console application:

' no error checking right now, just plain jane simple
Public Structure FancyInt

Public Value As Integer

Public Overloads Shared Narrowing Operator CType(ByVal source As String) As
FancyInt
Dim fi As FancyInt
fi.Value = CInt(source)
Return fi
End Operator

Public Overloads Shared Widening Operator CType(ByVal source As FancyInt)
As String
Return source.ToString
End Operator

Public Overrides Function ToString() As String
Return Value.ToString
End Function

Sub New(ByVal s As String)
Value = CInt(s)
End Sub

End Structure

Module Module1

Sub Main()
Console.WriteLine(New FancyInt("061091977")) 'good
Console.WriteLine(CType("061091977", Integer)) 'good
Console.WriteLine(CType("061091977", FancyInt)) 'good
Console.WriteLine(FancyConvert(Of Integer)("061091977"))' good
Console.WriteLine(FancyConvert(Of FancyInt)("061091977")) 'bad line 18
End Sub

Function FancyConvert(Of T As Structure)(ByVal o As Object) As T
Return CType(o, T) ' line 21
End Function

End Module

Here is the console output of the above Sub Main:

C:\>Test.exe

61091977
61091977
61091977
61091977
System.InvalidCastException: Specified cast is not valid.
at
Microsoft.VisualBasic.CompilerServices.Conversions .ToGenericParameter[T](Object Value)
at Test.Module1.FancyConvert[T](Object o) in
C:\TestProject\Module1.vb:line 21
at Test.Module1.Main() in C:\TestProject\Module1.vb:line 18

C:\>

So, what do I need to do to FancyInt so it is successfully cast just like
the Integer is successfully cast?

FYI - I also already tried implementing IConvertible on FancyInt as well as
tried implementing a TypeConverter along with applyng the TypeConverter
attribute on FancyInt, but no luck with either.

I must be missing something simple.

Any help?
Since your FancyConvert method uses Object as the parameter there is no
conversion routine from type Object to type FancyInt. And from what I
know, you aren't allowed to define a CType to convert from type Object.
You would get the same failure using CType directly as well.

Dim s As Object = "061091977" ' use type Object
Console.WriteLine(CType(s, FancyInt)) ' fails here
Aug 25 '07 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: bob scola | last post by:
I have a csharp, VS 2003 solution for a winform application The application uses an object called a "matter" and the class is defined in matter.cs. I can load matter objects into a combobox ...
5
by: Francois Malgreve | last post by:
in the following code: object obj = this.ViewState; string s = obj.GetType().ToString(); currentCreditLimit = (double) this.ViewState; ViewState is a StateBag object (dictionary type object)...
0
by: CowPad | last post by:
Hello All, I have a problem with serializing structs so I made a small application here to demonstrate. Hopefully someone can explain this strange problem. I have a Windows (Forms)...
1
by: Anders Berg | last post by:
Hi! I'm developing a very simple chat application in VB.NET and I've stumbled into a problem. For simplicity I'm using the TcpListener and TcpClient classes. However, at one point I discovered...
2
by: ajikoe | last post by:
Hi, I tried to follow the example in swig homepage. I found error which I don't understand. I use bcc32, I already include directory where my python.h exist in bcc32.cfg. /* File : example.c...
8
by: Gamma | last post by:
I'm trying to inherit subclass from System.Diagnostics.Process, but whenever I cast a "Process" object to it's subclass, I encounter an exception "System.InvalidCastException" ("Specified cast is...
9
by: Gaz | last post by:
This is as barebones as I can get it in order to explain my problem. **************************************************************************** using System; using System.Collections.Generic;...
15
by: Anthony Paul | last post by:
Let's say that I would like a generic type that supports Min/Max properties and can be double or integer or even datetime if need be, something flexible. So I go about creating the following...
1
by: =?Utf-8?B?QkpT?= | last post by:
I have written a Generic method that takes an object, a type, T, and returns a System.Nullable (Of T) depending on whether or not the object IsDBNull. It was working fine until I tried to pass a...
0
by: Roshawn | last post by:
Hi, I have a generic list of objects which I place in the cache. When trying to retrieve the data in the cache and place it in another object of the same type, I get an InvalidCastException. ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.