InvalidCastException from explicit casting object to a class

  • Thread starter Thread starter Kevin
  • Start date Start date
K

Kevin

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;

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 ConsoleApplication1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
struct Digit
{
byte value;

public Digit(byte value)
{
if (value > 9) throw new ArgumentException();
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.WriteLine("conversion occurred");
return d.value;
}
}

struct MyByte
{
byte value;

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

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

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);
}
}
}
 
Kevin said:
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;

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;
 
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.
 
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.
 
Kevin said:
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.
 
Back
Top