473,836 Members | 1,990 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

InvalidCastExce ption from explicit casting object to a class

Hi

I try the following program and I get InvalidCastExce ption at the line

MyByte b = (MyByte)obj;

If I change it to

MyByte b = (MyByte)d;

it works fine.

I need to convert the obj to MyByte type. Do you know a way to do it?

Thanks in advance.

using System;

namespace ConsoleApplicat ion1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
struct Digit
{
byte value;

public Digit(byte value)
{
if (value > 9) throw new ArgumentExcepti on();
this.value = value;
}

public byte ByteValue
{
get
{
return ( this.value );
}
set
{
this.value = value;
}
}
// define implicit Digit-to-byte conversion operator:
public static implicit operator byte(Digit d)
{
Console.WriteLi ne("conversion occurred");
return d.value;
}
}

struct MyByte
{
byte value;

public MyByte(byte value)
{
if (value > 9) throw new ArgumentExcepti on();
this.value = value;
}

// define implicit Digit-to-byte conversion operator:
public static implicit operator MyByte(Digit d)
{
Console.WriteLi ne("conversion occurred");
return new MyByte(d.ByteVa lue);
}
}

class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main()
{
Digit d = new Digit(3);
object obj = d;

MyByte b = (MyByte)obj;
System.Console. WriteLine(b);
}
}
}

Nov 15 '05 #1
4 3072
Kevin <ke************ **@hotmail.com> wrote:
I try the following program and I get InvalidCastExce ption at the line

MyByte b = (MyByte)obj;

If I change it to

MyByte b = (MyByte)d;

it works fine.

I need to convert the obj to MyByte type. Do you know a way to do it?


When you're unboxing, you need to unbox to the exact value type and
*then* you can do other conversions. So, you should be able to do:

MyByte b = (MyByte)(Digit) obj;

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
Well, if 'd' refers to an instance of MyByte, and 'obj' doesn't, then that
is why. You can't convert a type that is not compatible with MyByte to
MyByte.

This post makes no sense, as you didn't say what 'obj' is or what 'd' is.

"Kevin" <ke************ **@hotmail.com> wrote in message
news:Of******** *****@TK2MSFTNG P11.phx.gbl...
Hi

I try the following program and I get InvalidCastExce ption at the line

MyByte b = (MyByte)obj;

If I change it to

MyByte b = (MyByte)d;

it works fine.

I need to convert the obj to MyByte type. Do you know a way to do it?

Thanks in advance.

using System;

namespace ConsoleApplicat ion1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
struct Digit
{
byte value;

public Digit(byte value)
{
if (value > 9) throw new ArgumentExcepti on();
this.value = value;
}

public byte ByteValue
{
get
{
return ( this.value );
}
set
{
this.value = value;
}
}
// define implicit Digit-to-byte conversion operator:
public static implicit operator byte(Digit d)
{
Console.WriteLi ne("conversion occurred");
return d.value;
}
}

struct MyByte
{
byte value;

public MyByte(byte value)
{
if (value > 9) throw new ArgumentExcepti on();
this.value = value;
}

// define implicit Digit-to-byte conversion operator:
public static implicit operator MyByte(Digit d)
{
Console.WriteLi ne("conversion occurred");
return new MyByte(d.ByteVa lue);
}
}

class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main()
{
Digit d = new Digit(3);
object obj = d;

MyByte b = (MyByte)obj;
System.Console. WriteLine(b);
}
}
}


Nov 15 '05 #3
I am sorry that I don't state my problem clearly. I know that "MyByte b =
(MyByte)(Digit) obj;" works. Unfortunately, this call is in an external
library and I cannot change. I want to know if there is any other way to
make the casting from object to MyByte works.

Thanks.

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Kevin <ke************ **@hotmail.com> wrote:
I try the following program and I get InvalidCastExce ption at the line

MyByte b = (MyByte)obj;

If I change it to

MyByte b = (MyByte)d;

it works fine.

I need to convert the obj to MyByte type. Do you know a way to do it?


When you're unboxing, you need to unbox to the exact value type and
*then* you can do other conversions. So, you should be able to do:

MyByte b = (MyByte)(Digit) obj;

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #4
Kevin <ke************ **@hotmail.com> wrote:
I am sorry that I don't state my problem clearly. I know that "MyByte b =
(MyByte)(Digit) obj;" works. Unfortunately, this call is in an external
library and I cannot change. I want to know if there is any other way to
make the casting from object to MyByte works.


Not if the object in question isn't actually a MyByte, no.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #5

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

Similar topics

4
1427
by: Kevin | last post by:
Hi I try the following program and I get InvalidCastException at the line MyByte b = (MyByte)obj; If I change it to MyByte b = (MyByte)d;
1
3701
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);
4
1650
by: Chris Li | last post by:
I have the following classes: Public Class BaseClass { ... } Public Class DerivedClass: BaseClass { ...
4
2668
by: DOTNET | last post by:
Hi, Anybody help me regarding this error: I am assigning the values to the session variables when the button is clicked and passing these session variables to the next page and when I am printing these session variables they are printing. After that I am assigning these things in hidden object and in the form submit action I am receiving these hidden values like the following:
2
2660
by: John Richardson | last post by:
How does a custom casting operator work? I have a class that defines one, but doesn't work as expected (or perhaps, the way I want it to). I have the following example classes: ------------------ public class One : IOne { .... }//One public class Two {
6
343
by: Jim S | last post by:
I have a .net framework 2.0 client (Pocket PC) and a .net 2.0 webservice that communicate on the same LAN. The Pocket PC has no problem consuming strings returned from the web service methoeds but I’m unable to receive and a custom object. The error occurs when the PocketPC app casts a returned object (WebServiceServer.objectA) from the webservice to pocketPC.ObjectA (results in InvalidCastExeption). ObjectA is a simple class and is...
8
4275
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 {
1
2397
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...
4
3565
by: roynevo | last post by:
Hi, I'm trying to deserialize an object on the context of a remoting call (RPC). The deserialization seem to work fine, however when I'm casting the result to the relevant class I get an InvalidCastException. Note: * the remoting server has TypeFilterLevel to Full to remove security restrictions.
8
4968
by: Joe HM | last post by:
Hello - I was wondering that the "cleanest" way is to determine whether a CType() will throw an InvalidCastException? I have data I receive as an Object and I want to convert it to a String whenever possible using CType(lObjectDummy, String) otherwise I will just ignore it. I could put a Try/Catch As System.InvalidCastException around it but I was wondering if that is the best solution. I once heard that exceptions should not be...
0
9656
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
10819
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...
0
10526
jinu1996
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...
0
10240
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
9355
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
7772
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...
1
4438
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
2
4000
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3100
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.