Inconsistent Documentation for Unary Operator -

J

Javier Estrada

1. For types smaller than int, when I compile:

class MyClass
{

static void Main(string[] args)
{
[type] x = 10;
[type] y = -x;
}
}

where [type] is one of {sbyte, byte, short, ushort},

I receive error CS0029: Cannot implicitly convert
type 'int' to 'type'

2. When I compile with int, uint, long, no problem.

3. When I compile using ulong I receive error CS0023:
Operator '-' cannot be applied to operand of type 'ulong'

According to the documentation for the unary operator -
"Unary - operators are predefined for ALL numeric types.
The result of a unary - operation on a numeric type is
the negation of the operand."

Emphasis on ALL is mine.

This documentation is MISLEADING, since section 7.6.2 of
the C# Language Specification states that there are only
two unary operator overloads: for int and long, along
with the conversion rules.

Regards,

Javier

Please respond to the newsgroup so everybody can benefit
from the answer.
 
J

Jon Skeet

Joe said:
Per Para 9.4.4.2 of the C# spec, 10 is an integer literal and may be
evaluated as int, unint, long or ulong. Therefore, 10 will not evaluate to
sbyte, byte, short, or ushort. Per chapter 13 of the spec. assignment of
int, unint, long or ulong to sbyte, byte, short, or ushort requires and
explicit conversion and you must use the cast operator.

Hmm... I see the bits of the spec you mean, but I was confused as to
why this then compiles and runs without any problem:

using System;

public class Test
{
static void Main()
{
byte b = 10;
Console.WriteLine (b);
}
}

And then I found section 14.13, which explains it all, although not
very clearly.
 
J

Joe

Jon Skeet said:
Hmm... I see the bits of the spec you mean, but I was confused as to
why this then compiles and runs without any problem:

using System;

public class Test
{
static void Main()
{
byte b = 10;
Console.WriteLine (b);
}
}

And then I found section 14.13, which explains it all, although not
very clearly.

Right. ;) The last paragraph of section 14.15 explains why your example is
correct. So, the real error was generated by the results of the unary minus
operator that returned an int. I believe that section 14.13 makes a little
more sense when clarified by section 14.6.2, which defines the return types
of the unary minus operator. BTW, I think the original poster accidently
mistyped the section number 7.6.2, when he really meant 14.6.2.

Joe
 

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

Top