Question

I don't usually deal with hexadecimal numbers unless I am working with HTML, so I really do not have much experience converting code that involves them. Essentially, the problem here is that I am converting some classes from VB.NET to C#.NET and there are a couple places where the VB version is comparing some value to a Hex constant. When I translate the value to its C# equivalent, I get the following "warning" message from Visual Studio:

Comparison to integral constant is useless, the constant is outside the range of type 'int'

Now, obviously the VB version does not have this warning or I wouldn't bother asking this question. I will note that if I cast the Property being compared as Int64 the warning goes away.

What I want to know is whether I have done this right and if I shouldn't just scrap the whole comparison since it apparently will not work in a real-world scenario?

VB Code:

    Catch ex As COMException
        If bInsert AndAlso ex.ErrorCode = &H80042776 Then
            ' DO THINGS
    End Try

C# Code:

        catch (COMException come)
        {
            if (insert && come.ErrorCode == 0x80042776)
            {
                // DO THINGS
            }
        }
Was it helpful?

Solution

I don't know if this has worked in VB.NET (not sure of the rules there), but C# will not easily let you specify a negative number like that. I think you have to say

...    come.ErrorCode == unchecked((int)0x80042776)

Otherwise C# will not regard it as a negative 32-bit integer, I'm afraid. Even if your code is already compiled in unchecked context (which I bet it is!), you still have to write unchecked explicitly like above, when it's a compile-time constant you're "converting".

Irritating when 8 hex digits fit nicely to 32 bit (System.Int32).

OTHER TIPS

In VB.NET, when it comes to integer literals:

values outside the range for Integer are typed as Long

COMException::ErrorCode is of type int32. So it's biggest value is 2^31 - 1. (2,147,483,647).

You are comparing with a hex number 0x80042776. With a decimal value of 2,147,755,894.

These numbers are pretty close, but notice that the hex one is bigger than the biggest number an int32 can possibly be. That's what the compiler is warning you about. The same is true in VB, it's just that the compiler isn't warning you about it.

Where did the magic hex constant come from? It's probably wrong.

OK, so I did some additional searching on the issue (probably should have done this first), and found the answer I was looking for. It turns out that COMException's ErrorCode is actually an UNSIGNED integer (see HRESULT). Maybe VB automatically handles this, too?

The stack overflow post I saw that detailed this is here: Catching COMException specific Error Code - look at the chosen answer to the question

I would like to hear back from other people about this one before I mark an answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top