By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,987 Members | 1,467 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,987 IT Pros & Developers. It's quick & easy.

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

P: n/a
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
Apr 5 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a

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

Apr 5 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.