473,804 Members | 2,962 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem: InvalidCastExce ption 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 InvalidCastExce ption.
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.Com pilerServices.C onversions.ToGe nericParameter 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.WriteLi ne(New FancyInt("06109 1977")) 'good
Console.WriteLi ne(CType("06109 1977", Integer)) 'good
Console.WriteLi ne(CType("06109 1977", FancyInt)) 'good
Console.WriteLi ne(FancyConvert (Of Integer)("06109 1977"))' good
Console.WriteLi ne(FancyConvert (Of FancyInt)("0610 91977")) 'bad line 18
End Sub

Function FancyConvert(Of T As Structure)(ByVa l 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.InvalidC astException: Specified cast is not valid.
at
Microsoft.Visua lBasic.Compiler Services.Conver sions.ToGeneric Parameter[T](Object Value)
at Test.Module1.Fa ncyConvert[T](Object o) in
C:\TestProject\ Module1.vb:line 21
at Test.Module1.Ma in() 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 2395


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 InvalidCastExce ption.
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.Com pilerServices.C onversions.ToGe nericParameter 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.WriteLi ne(New FancyInt("06109 1977")) 'good
Console.WriteLi ne(CType("06109 1977", Integer)) 'good
Console.WriteLi ne(CType("06109 1977", FancyInt)) 'good
Console.WriteLi ne(FancyConvert (Of Integer)("06109 1977"))' good
Console.WriteLi ne(FancyConvert (Of FancyInt)("0610 91977")) 'bad line 18
End Sub

Function FancyConvert(Of T As Structure)(ByVa l 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.InvalidC astException: Specified cast is not valid.
at
Microsoft.Visua lBasic.Compiler Services.Conver sions.ToGeneric Parameter[T](Object Value)
at Test.Module1.Fa ncyConvert[T](Object o) in
C:\TestProject\ Module1.vb:line 21
at Test.Module1.Ma in() 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.WriteLi ne(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
3700
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 Matter matters= v.Matters; comboBox1.Items.AddRange(matters);
5
2389
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) the String s shows me that the type is System.Int32, the value contained is 0 ( I can see it in the debugger)
1
1741
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 that I want to use the protected Active and Client properties of the TcpClient class. To do this I made my own derived class: Public Class MyTcpClient Inherits TcpClient
2
4456
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 */ #include <time.h>
8
4274
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 not valid"). How do I fix it ? using System.Diagnostics; .. .. class NewProcess: Process {
9
1410
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; using System.Text; namespace ConsoleApplication1 { class Program
15
7104
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 generic interface : *note : in reality I implement the IComparable and IEquatable generic interfaces and associated overriden methods, but I've cut everything down to the bare minimum for this example.
1
2246
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 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...
0
915
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. Here's my code: 'global variable Dim fItems as List (Of Item)'Item is a custom object
0
9704
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9571
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10302
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10069
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9132
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7608
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6845
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5505
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2976
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.