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);
}
}
}
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);
}
}
}