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

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

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:
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?!


regards,
martin
 
martin said:
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/d...y/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."
 
Back
Top