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? 1 2247
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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);
|
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)
|
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)
|
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
|
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>
| |
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
{
|
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
|
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.
|
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...
|
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
|
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,...
| |
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...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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...
|
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...
|
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();...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |