Hi
I have two constant integers and when I try to compare their values, I get
error:
Operator '==' cannot be applied to operands of type ...
Here is a cut down version of my code
public class MY_CONSTANTS
{
public const int FOO = 1;
...
}
MY_CONSTANTS m_value = MY_CONSTANTS.FOO;
public bool Bar(MY_CONSTANTS val)
{
return m_value == val; // Errors.
}
Is there a way around this?
Thanks
Paul E Collins - 12 Oct 2007 09:40 GMT
> I have two constant integers and when I try to compare
> their values, I get error:
[quoted text clipped - 9 lines]
>
> MY_CONSTANTS m_value = MY_CONSTANTS.FOO;
MY_CONSTANTS.FOO is not a MY_CONSTANTS instance. It is an int, so you
would have to make m_value an int as well.
Alternatively, make MY_CONSTANTS an enum instead of a class.
Eq.
Amir Tohidi - 12 Oct 2007 09:47 GMT
Hi
I managed to get around the problem using a struct and implicit operator. Is
this the right approach?
public struct MY_CONSTANTS // changed to struct
{
public const int FOO = 1;
...
public MY_CONSTANTS(MY_CONSTANTS value)
{
m_value = Convert.ToInt32(value);
}
public static implicit operator int(MY_CONSTANTS c)
{
return Convert.ToInt32(c.m_value);
}
private int m_value;
}
> Hi
>
[quoted text clipped - 21 lines]
>
> Thanks
Jon Skeet [C# MVP] - 12 Oct 2007 09:52 GMT
On Oct 12, 9:47 am, Amir Tohidi <AmirToh...@discussions.microsoft.com>
wrote:
> I managed to get around the problem using a struct and implicit operator. Is
> this the right approach?
No - I'd use an enum instead.
Jon
Ben Voigt [C++ MVP] - 12 Oct 2007 18:57 GMT
> On Oct 12, 9:47 am, Amir Tohidi <AmirToh...@discussions.microsoft.com>
> wrote:
[quoted text clipped - 3 lines]
>
> No - I'd use an enum instead.
An enum isn't extensible though... sometimes the struct with a single
integer field is better.
> Jon
Jon Skeet [C# MVP] - 12 Oct 2007 19:04 GMT
> > No - I'd use an enum instead.
>
> An enum isn't extensible though... sometimes the struct with a single
> integer field is better.
Occasionally - but in that case I'd use an alternative enum-like
pattern such that the integer value was hidden, or expose it via a
property. Implicit conversions are almost always a bad idea, IMO. (In
fact, just today I fixed a bug due to a conversion. It was very hard to
track down because it just wasn't obvious what was going on when you
looked at the C# code. The IL made it a lot clearer.)

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too