Given the code below:
static void Main()
{
Console.WriteLine(typeof(MyEnum).BaseType.FullName);
}
enum MyEnum : ushort
{
One = 1,
Two = 2
}
It outputs System.Enum, which means the colon here has nothing to do with inheritance, and it just specifies the basic type of the enum, am I right?
But if I change my code as follows:
enum MyEnum : UInt16
{
One = 1,
Two = 2
}
I would get a compilation error. Why? Aren't UInt16 and ushort the same?
You are correct that reflection doesn't report that an enum inherits the base type, which the specification calls the "underlying type". You can find it using Enum.GetUnderlyingType instead.
The type named by ushort and System.UInt16 are precisely the same.
However, the syntax of enum does not call for a type. Instead it calls for one of a limited set of keywords, which control the underlying type. While System.UInt16 is a valid underlying type, it is not one of the keywords which the C# grammar permits to appear in that location.
Quoting the grammar:
enum-declaration:
attributesopt enum-modifiersopt enum identifier enum-baseopt enum-body ;opt
enum-base:
: integral-type
integral-type:
sbyte
byte
short
ushort
int
uint
long
ulong
char
Because the valid types for an enum are explicitly specified to be the integral types (except char).
The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
http://msdn.microsoft.com/en-us/library/sbbt4032.aspx
One would expect the UInt16 to be equivalent to a ushort given the documentation for built in types:
The C# type keywords and their aliases are interchangeable. For example, you can declare an integer variable by using either of the following declarations...
http://msdn.microsoft.com/en-us/library/ya5y69ds.aspx
Edit: I had messed around with this answer a few times not quite grasping the correct answer. #BenVoight is correct. The accepted list are the integral types (other than char) The System.UInt16 is exactly the same type as ushort, but it is not an integral type identifier (merely a struct type) as specified by the grammar.
That's compiler error CS1008, and it pretty much provides the answer. The approved types for an enum:
The approved types for an enum are byte, sbyte, short, ushort, int,
uint, long, or ulong.
The first part of your question is answered by others, but no one has addressed the 2nd part yet. Someone other than the OP has since edited the 2nd question, my answer may no longer apply
UInt16 and UInt are not the same, UInt16 is an unsigned 16 bit integer, UInt is an unsigned 32 bit integer. They vary quite a bit in their maximum value.
Just for completeness, I'm including the answer to the. first question also:
The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
As for why?
My guess is CLS compliance.
Related
If I have two bytes a and b, how come:
byte c = a & b;
produces a compiler error about casting byte to int? It does this even if I put an explicit cast in front of a and b.
Also, I know about this question, but I don't really know how it applies here. This seems like it's a question of the return type of operator &(byte operand, byte operand2), which the compiler should be able to sort out just like any other operator.
Why do C#'s bitwise operators always return int regardless of the format of their inputs?
I disagree with always. This works and the result of a & b is of type long:
long a = 0xffffffffffff;
long b = 0xffffffffffff;
long x = a & b;
The return type is not int if one or both of the arguments are long, ulong or uint.
Why do C#'s bitwise operators return int if their inputs are bytes?
The result of byte & byte is an int because there is no & operator defined on byte. (Source)
An & operator exists for int and there is also an implicit cast from byte to int so when you write byte1 & byte2 this is effectively the same as writing ((int)byte1) & ((int)byte2) and the result of this is an int.
This behavior is a consequence of the design of IL, the intermediate language generated by all .NET compilers. While it supports the short integer types (byte, sbyte, short, ushort), it has only a very limited number of operations on them. Load, store, convert, create array, that's all. This is not an accident, those are the kind of operations you could execute efficiently on a 32-bit processor, back when IL was designed and RISC was the future.
The binary comparison and branch operations only work on int32, int64, native int, native floating point, object and managed reference. These operands are 32-bits or 64-bits on any current CPU core, ensuring the JIT compiler can generate efficient machine code.
You can read more about it in the Ecma 335, Partition I, chapter 12.1 and Partition III, chapter 1.5
I wrote a more extensive post about this over here.
Binary operators are not defined for byte types (among others). In fact, all binary (numeric) operators act only on the following native types:
int
uint
long
ulong
float
double
decimal
If there are any other types involved, it will use one of the above.
It's all in the C# specs version 5.0 (Section 7.3.6.2):
Binary numeric promotion occurs for the operands of the predefined +, –, *, /, %, &, |, ^, ==, !=, >, <, >=, and <= binary operators. Binary numeric promotion implicitly converts both operands to a common type which, in case of the non-relational operators, also becomes the result type of the operation. Binary numeric promotion consists of applying the following rules, in the order they appear here:
If either operand is of type decimal, the other operand is converted to type decimal, or a compile-time error occurs if the other operand is of type float or double.
Otherwise, if either operand is of type double, the other operand is converted to type double.
Otherwise, if either operand is of type float, the other operand is converted to type float.
Otherwise, if either operand is of type ulong, the other operand is converted to type ulong, or a compile-time error occurs if the other operand is of type sbyte, short, int, or long.
Otherwise, if either operand is of type long, the other operand is converted to type long.
Otherwise, if either operand is of type uint and the other operand is of type sbyte, short, or int, both operands are converted to type long.
Otherwise, if either operand is of type uint, the other operand is converted to type uint.
Otherwise, both operands are converted to type int.
It's because & is defined on integers, not on bytes, and the compiler implicitly casts your two arguments to int.
If I have two bytes a and b, how come:
byte c = a & b;
produces a compiler error about casting byte to int? It does this even if I put an explicit cast in front of a and b.
Also, I know about this question, but I don't really know how it applies here. This seems like it's a question of the return type of operator &(byte operand, byte operand2), which the compiler should be able to sort out just like any other operator.
Why do C#'s bitwise operators always return int regardless of the format of their inputs?
I disagree with always. This works and the result of a & b is of type long:
long a = 0xffffffffffff;
long b = 0xffffffffffff;
long x = a & b;
The return type is not int if one or both of the arguments are long, ulong or uint.
Why do C#'s bitwise operators return int if their inputs are bytes?
The result of byte & byte is an int because there is no & operator defined on byte. (Source)
An & operator exists for int and there is also an implicit cast from byte to int so when you write byte1 & byte2 this is effectively the same as writing ((int)byte1) & ((int)byte2) and the result of this is an int.
This behavior is a consequence of the design of IL, the intermediate language generated by all .NET compilers. While it supports the short integer types (byte, sbyte, short, ushort), it has only a very limited number of operations on them. Load, store, convert, create array, that's all. This is not an accident, those are the kind of operations you could execute efficiently on a 32-bit processor, back when IL was designed and RISC was the future.
The binary comparison and branch operations only work on int32, int64, native int, native floating point, object and managed reference. These operands are 32-bits or 64-bits on any current CPU core, ensuring the JIT compiler can generate efficient machine code.
You can read more about it in the Ecma 335, Partition I, chapter 12.1 and Partition III, chapter 1.5
I wrote a more extensive post about this over here.
Binary operators are not defined for byte types (among others). In fact, all binary (numeric) operators act only on the following native types:
int
uint
long
ulong
float
double
decimal
If there are any other types involved, it will use one of the above.
It's all in the C# specs version 5.0 (Section 7.3.6.2):
Binary numeric promotion occurs for the operands of the predefined +, –, *, /, %, &, |, ^, ==, !=, >, <, >=, and <= binary operators. Binary numeric promotion implicitly converts both operands to a common type which, in case of the non-relational operators, also becomes the result type of the operation. Binary numeric promotion consists of applying the following rules, in the order they appear here:
If either operand is of type decimal, the other operand is converted to type decimal, or a compile-time error occurs if the other operand is of type float or double.
Otherwise, if either operand is of type double, the other operand is converted to type double.
Otherwise, if either operand is of type float, the other operand is converted to type float.
Otherwise, if either operand is of type ulong, the other operand is converted to type ulong, or a compile-time error occurs if the other operand is of type sbyte, short, int, or long.
Otherwise, if either operand is of type long, the other operand is converted to type long.
Otherwise, if either operand is of type uint and the other operand is of type sbyte, short, or int, both operands are converted to type long.
Otherwise, if either operand is of type uint, the other operand is converted to type uint.
Otherwise, both operands are converted to type int.
It's because & is defined on integers, not on bytes, and the compiler implicitly casts your two arguments to int.
I would like to know, is there any posibility in C# to change default (integer) representation of enum to something with less weight like char.
Many of you will ask me why I want to do it? Answer is simple:
I have to work at huge, huge Array.
My PC allow me to allocate memory for array of integer with 540 000 000 elements (2048 * 2048 * 128). Everyone know integer needs aroud 4 times more memory than Char.
Char representation give me 2 000 000 000 elements to manipulate.
Much easier in programming masive algorithms is to work at Enum than char but if the change of representation isn't possible I will have to work on charracters.
Yes, you can change the type of an enum but not to char. For your byte can work well as it's 1 byte type. Check enum (C# reference) on MSDN (emphasis mine):
Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of enumeration elements is int. To declare an enum of another integral type, such as byte, use a colon after the identifier followed by the type, as shown in the following example.
enum Days : byte {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
Yes you can specify the underlying type
public enum MyEnum : byte
{
}
enum MyEnum : byte
{
...
That's all.
You can specify underlying type of enum. From enum (C# Reference):
Every enumeration type has an underlying type, which can be any
integral type except char. The default underlying type of enumeration
elements is int. To declare an enum of another integral type, such as
byte, use a colon after the identifier followed by the type
public enum YourEnum : byte
{
Foo,
Bar
}
The documentation shows you how.
Every enumeration type has an underlying type, which can be any
integral type except char. The default underlying type of enumeration
elements is int. To declare an enum of another integral type, such as
byte, use a colon after the identifier followed by the type, as shown
in the following example.
enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
Note well that in C# char is two bytes wide. You presumably mean to use byte. But as you can see from the documentation, the compiler would have rejected your attempt to use char.
Simply declare the enum of another integral type such as byte like this:
Public enum MyEnum : byte {}
In my understanding literal integers belong to System.Int32 by default. If so why can we assign a literal integer of type System.Int32 to short x without casting?
short x = 1;//compilable
Why don't we need to use casting as follows?
short x = (short)1;
Because the specification allows for that in section 6.1.9:
A constant expression of type int can be converted to sbyte, byte,
short, ushort, uint, or ulong, provided the value of the constant
expression is within the range of the destination type.
The 1 is indeed a constant expression of type int because (section 2.4.4.2, "Integer literals"):
The type of an integer literal is determined as follows:
If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.
I have a question about the implicit type conversion
Why does this implicit type conversion work in C#? I've learned that implicit code usually don't work.
I have a code sample here about implicit type conversion
char c = 'a';
int x = c;
int n = 5;
int answer = n * c;
Console.WriteLine(answer);
UPDATE: I am using this question as the subject of my blog today. Thanks for the great question. Please see the blog for future additions, updates, comments, and so on.
http://blogs.msdn.com/ericlippert/archive/2009/10/01/why-does-char-convert-implicitly-to-ushort-but-not-vice-versa.aspx
It is not entirely clear to me what exactly you are asking. "Why" questions are difficult to answer. But I'll take a shot at it.
First, code which has an implicit conversion from char to int (note: this is not an "implicit cast", this is an "implicit conversion") is legal because the C# specification clearly states that there is an implicit conversion from char to int, and the compiler is, in this respect, a correct implementation of the specification.
Now, you might sensibly point out that the question has been thoroughly begged. Why is there an implicit conversion from char to int? Why did the designers of the language believe that this was a sensible rule to add to the language?
Well, first off, the obvious things which would prevent this from being a rule of the language do not apply. A char is implemented as an unsigned 16 bit integer that represents a character in a UTF-16 encoding, so it can be converted to a ushort without loss of precision, or, for that matter, without change of representation. The runtime simply goes from treating this bit pattern as a char to treating the same bit pattern as a ushort.
It is therefore possible to allow a conversion from char to ushort. Now, just because something is possible does not mean it is a good idea. Clearly the designers of the language thought that implicitly converting char to ushort was a good idea, but implicitly converting ushort to char is not. (And since char to ushort is a good idea, it seems reasonable that char-to-anything-that-ushort-goes-to is also reasonable, hence, char to int. Also, I hope that it is clear why allowing explicit casting of ushort to char is sensible; your question is about implicit conversions.)
So we actually have two related questions here: First, why is it a bad idea to allow implicit conversions from ushort/short/byte/sbyte to char? and second,
why is it a good idea to allow implicit conversions from char to ushort?
Unlike you, I have the original notes from the language design team at my disposal. Digging through those, we discover some interesting facts.
The first question is covered in the notes from April 14th, 1999, where the question of whether it should be legal to convert from byte to char arises. In the original pre-release version of C#, this was legal for a brief time. I've lightly edited the notes to make them clear without an understanding of 1999-era pre-release Microsoft code names. I've also added emphasis on important points:
[The language design committee] has chosen to provide
an implicit conversion from bytes to
chars, since the domain of one is
completely contained by the other.
Right now, however, [the runtime
library] only provide Write methods
which take chars and ints, which means
that bytes print out as characters
since that ends up being the best
method. We can solve this either by
providing more methods on the Writer
class or by removing the implicit
conversion.
There is an argument for why the
latter is the correct thing to do.
After all, bytes really aren't
characters. True, there may be a
useful mapping from bytes to chars, but ultimately, 23 does not denote the
same thing as the character with ascii
value 23, in the same way that 23B
denotes the same thing as 23L. Asking
[the library authors] to provide this
additional method simply because of
how a quirk in our type system works
out seems rather weak. So I would
suggest that we make the conversion
from byte to char explicit.
The notes then conclude with the decision that byte-to-char should be an explicit conversion, and integer-literal-in-range-of-char should also be an explicit conversion.
Note that the language design notes do not call out why ushort-to-char was also made illegal at the same time, but you can see that the same logic applies. When calling a method overloaded as M(int) and M(char), when you pass it a ushort, odds are good that you want to treat the ushort as a number, not as a character. And a ushort is NOT a character representation in the same way that a ushort is a numeric representation, so it seems reasonable to make that conversion illegal as well.
The decision to make char go to ushort was made on the 17th of September, 1999; the design notes from that day on this topic simply state "char to ushort is also a legal implicit conversion", and that's it. No further exposition of what was going on in the language designer's heads that day is evident in the notes.
However, we can make educated guesses as to why implicit char-to-ushort was considered a good idea. The key idea here is that the conversion from number to character is a "possibly dodgy" conversion. It's taking something that you do not KNOW is intended to be a character, and choosing to treat it as one. That seems like the sort of thing you want to call out that you are doing explicitly, rather than accidentally allowing it. But the reverse is much less dodgy. There is a long tradition in C programming of treating characters as integers -- to obtain their underlying values, or to do mathematics on them.
In short: it seems reasonable that using a number as a character could be an accident and a bug, but it also seems reasonable that using a character as a number is deliberate and desirable. This asymmetry is therefore reflected in the rules of the language.
Does that answer your question?
The basic idea is that conversions leading to potential data-loss can be implicit, whereas conversions, which may lead to data-loss have to be explicit (using, for instance, a cast operator).
So implicitly converting from char to int will work in C#.
[edit]As others pointed out, a char is a 16-bit number in C#, so this conversion is just from a 16-bit integer to a 32-bit integer, which is possible without data-loss.[/edit]
C# supports implicit conversions, the part "usually don't work" is probably coming from some other language, probably C++, where some glorious string implementations provided implicit conversions to diverse pointer-types, creating some gigantic bugs in applications.
When you, in whatever language, provide type-conversions, you should also default to explicit conversions by default, and only provide implicit conversions for special cases.
From C# Specification
6.1.2 Implicit numeric conversions
The implicit numeric conversions are:
• From sbyte to short, int, long,
float, double, or decimal.
• From byte to short, ushort, int,
uint, long, ulong, float, double, or
decimal.
• From short to int, long, float,
double, or decimal.
• From ushort to int, uint, long,
ulong, float, double, or decimal.
• From int to long, float, double, or
decimal.
• From uint to long, ulong, float,
double, or decimal.
• From long to float, double, or
decimal.
• From ulong to float, double, or
decimal.
• From char to ushort, int, uint,
long, ulong, float, double, or
decimal.
• From float to double.
Conversions from int, uint, long, or
ulong to float and from long or ulong
to double may cause a loss of
precision, but will never cause a loss
of magnitude. The other implicit
numeric conversions never lose any
information. There are no implicit
conversions to the char type, so
values of the other integral types do
not automatically convert to the char
type.
From the MSDN page about the char (char (C# Reference) :
A char can be implicitly converted to ushort, int, uint, long, ulong, float, double, or decimal. However, there are no implicit conversions from other types to the char type.
It's because they have implemented an implicit method from char to all those types. Now if you ask why they implemented them, I'm really not sure, certainly to help working with ASCII representation of chars or something like that.
Casting will cause data loss. Here char is 16 bit and int is 32 bit. So the cast will happen without loss of data.
Real life example: we can put a small vessel into a big vessel but not vice versa without external help.
The core of #Eric Lippert's blog entry is his educated guess for the reasoning behind this decision of the c# language designers:
"There is a long tradition in C programming of treating characters as integers
-- to obtain their underlying values, or to do mathematics on them."
It can cause errors though, such as:
var s = new StringBuilder('a');
Which you might think initialises the StringBuilder with an 'a' character to start with, but actually sets the capacity of the StringBuilder to 97.
It works because each character is handled internally as a number, hence the cast is implicit.
The char is implicitly cast to it's Unicode numeric value, which is an integer.
The implicit conversion from char to number types makes no sense, in my opinion, because a loss of information happens. You can see it from this example:
string ab = "ab";
char a = ab[0];
char b = ab[1];
var d = a + b; //195
We have put all pieces of information from the string into chars. If by any chance only the information from d is kept, all that is left to us is a number which makes no sense in this context and cannot be used to recover the previously provided information. Thus, the most useful way to go would be to implicitly convert the "sum" of chars to a string.