Re: Passing zero (int) to an enum in .NET Socket constructor?!




martin wrote:
This code compiles (this is how it should work):
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);

This code does not compile (passing an int instead of an AddressFamily is
bad):
Socket sock = new Socket(1, SocketType.Stream, ProtocolType.Tcp);

But why on earth does not compile:

Typo, I assume.

Socket sock = new Socket(0, SocketType.Stream, ProtocolType.Tcp);

Is the number zero some kind of special case here? Why is zero accepted when
the parameter type clearly says that an AddressFamily enum value is expected?!

Yes, zero is a special case. Here is a shorter example:

System.Net.Sockets.AddressFamily af1 = 1; // no compile
System.Net.Sockets.AddressFamily af1 = 0; // compile

The reason can be found in section 6.1.3 of the C# spec:

<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csspec/html/vclrfcsharpspec_6_1_2.asp>

(sic, the url says 6.1.2 but the page is 6.1.3 :))


C# Language Specification

6.1.3 Implicit enumeration conversions
An implicit enumeration conversion permits the decimal-integer-literal
0 to be converted to any enum-type.


Elsewhere in the docs, we are also told "The default value of an enum E
is the value produced by the expression (E)0."

--
Larry Lard
Replies to group please

.



Relevant Pages

  • Re: D3/Linux compile question
    ... 02 equ a to x ... Variable has not been assigned a value; zero used. ... Based on the actual compile I'm not sure. ... base frame not 1 past the base frame. ...
    (comp.databases.pick)
  • Re: Two problems
    ... uninitialised variables that I really should be clearing to zero ... I don't need a statement clearing the variable ... In one case they are set to zero or some other ... enabled and turn on all of the compile time warnings you can. ...
    (comp.lang.fortran)
  • Re: Two problems
    ... uninitialised variables that I really should be clearing to zero ... I don't need a statement clearing the variable ... In one case they are set to zero or some other ... enabled and turn on all of the compile time warnings you can. ...
    (comp.lang.fortran)
  • Re: Division by zero
    ... when Y is a static expression equal to 0. ... The reason is that it simplifies the language definition. ... - always detect this error at compile time ... For division by zero, it is believed to be too restrictive to detect it ...
    (comp.lang.ada)
  • Re: Use of memcpy() to transfer from memory to a variable
    ... It is if it produces a trap representation in the 'long' variable. ... where it can produce negative zero, which can be a trap representation. ... it's possible to trap it at compile time by checking that ... memcpy(&value, pAddress, rem); ...
    (comp.lang.c)