473,960 Members | 8,560 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 2255


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
3709
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
2398
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)
0
1099
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) application that calls this function in a button click event: --------------------------------------------------------- private void button1_Click(object sender, System.EventArgs e)
1
1750
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
4473
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
4290
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
1415
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
7126
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
2407
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
921
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
10278
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
10103
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,...
0
11740
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
11490
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
10822
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...
1
8393
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
6328
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...
0
6472
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4668
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.