Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# returning UInt32 vs Int32 - C# thinking 0 and 1 are Int32

Tags:

c#

I'm working on a C# dll bind to UDK, in which you have to return a unsigned 32 bit integer for bool values - hence 0 is false, anything greater is true. The UDK gets the value and converts it to either true or false...

I was doing some code and found this:

[DllExport("CheckCaps", CallingConvention = CallingConvention.StdCall)]
    public static UInt32 CheckCaps()
    {
        return ( Console.CapsLock ? 1 : 0);
    }

gave me the error of:

"Error, Cannot implicitly convert type 'int' to 'uint'. An explicit conversion exists (are you missing a cast?)"

While I understand the error, I didnt have this issue before doing

            if (File.Exists(filepath))
            return 1;
        else
            return 0;

From the way it looks like C#'s issue with string typecasting, where if you have this:

int example = 5;
Console.Writeline( example);
Console.Writeline( example + "");

The first console.writeline will give an error because C# won't autotype cast to a string

I understand that there are logical reasons behind these errors (as they occur in these situations) , but is there a fix for this other than doing Convert.ToUInt32(1) and Convert.ToUInt32(0)?

(I'm hoping for a fix akin to how you can go 0.f for floats, but for unsigned intergers)

like image 228
Gareth Jones Avatar asked Aug 10 '13 01:08

Gareth Jones


2 Answers

The code below

if (File.Exists(filepath))
    return 1;
else
    return 0;

compiles because according to C# standard

13.1.7 A constant-expression (§14.16) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type.

There is no implicit conversion like that defined for conditional expressions, so your first code snippet needs either an explicit cast or a U suffix:

return Console.CapsLock ? 1U : 0;

Note that only one conversion/suffix is necessary, because zero can be converted to uint based on the rule 13.1.7 above.

like image 113
Sergey Kalinichenko Avatar answered Sep 27 '22 17:09

Sergey Kalinichenko


1u is the unsigned literal syntax for 1. 0u is for 0.

like image 31
recursive Avatar answered Sep 27 '22 17:09

recursive