Why enums can convert to IntPtr?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Consider the following code snippet:

using System;
enum E { A, }
struct T
{
public static explicit operator T(int i) { return new T(); }
public static void Foo()
{
E e = 0;
IntPtr ptr = (IntPtr)e; // case 1: compiles fine
T t = (T)e; // case 2: gives an error in correspondence with the specs
}
}

Microsoft C# compiler gives an error in case 2 (which follows the specs). In
case 1 the code compiles fine.
Does the compiler follow the specs in case 1? If so, where is the
description of that case in the specs?

I used C# compiler from VS 2003 and 2.0 November preview.

Thanks,
andy
 
cody said:
Boxing can only occur with type "object" and nothing else.

Not true - it also occurs with interfaces. For instance:

int x = 5;
IComparable ic = x; // Boxing here

I don't think that's what's going on here, but I thought it was worth
being precise :)
 
E e = 0;
IntPtr ptr = (IntPtr)e; // case 1: compiles fine
Does the compiler follow the specs in case 1? If so, where is the
description of that case in the specs?

I looked in the spec and came to the conclusion that the compiler isn't
following the spec. The only way this could possibly work is by using the
explicit conversion operator.

public static explicit operator IntPtr(int value);

This however requires that we have two valid Standard Conversions. One from
IntPtr->IntPtr and one from E->int. The first is an identity conversion,
but the second seem to have neither an implicit or explicit standard
conversion as far as I can see.
 
Thanks Marcus,

I also think that the specs do not reflect the compiler behavior. Just
wanted to make sure that I do not misread them.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top