Compare two integer constants

G

Guest

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
 
P

Paul E Collins

Amir Tohidi said:
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;

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.
 
G

Guest

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

Jon Skeet [C# MVP]

Ben Voigt said:
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.)
 

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

Similar Threads


Top