473,791 Members | 3,059 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);
}
}
}

Jul 21 '05 #1
4 1424
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
Jul 21 '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);
}
}
}


Jul 21 '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

Jul 21 '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
Jul 21 '05 #5

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);
4
3071
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;
4
1649
by: Chris Li | last post by:
I have the following classes: Public Class BaseClass { ... } Public Class DerivedClass: BaseClass { ...
4
2664
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
2658
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
4273
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
2395
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.
0
9512
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
10419
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
10201
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...
1
10147
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
9987
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
6770
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
5424
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
5552
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2910
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.