Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does accessing an Enum member not present in the enum definition (via casting an integer) not give an error

Tags:

c#

.net

enums

To fix a bug in my application, I had to set the SecurityProtocolType of the ServicePointManager class found in the System.Net assembly like this:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

In .Net 4.5+ the SecurityProtocolType enum has four members:

public enum SecurityProtocolType
{
    Ssl3 48,    
    Tls 192,    
    Tls11 768,  
    Tls12 3072
}

However, in .Net 4.0 the SecurityProtocolType enum has only two members:

public enum SecurityProtocolType
{
    Ssl3 48,    
    Tls 192
}

Since, another project in my code also needed the same fix but that project was on .Net 4.0 which does not have Tls12 as a member for the enum, this answer suggested the following workaround (provided I have the .Net 4.5 installed on the same box):

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

May be I am missing smoething obvious, but my question is, how does (SecurityProtocolType)3072 get resolved to Tls12 when 3072 is not a valid value for the enum in .Net 4.0. I want to understand what magic is going on behind the scenes that makes this work.

like image 541
Punit Vora Avatar asked Oct 24 '18 19:10

Punit Vora


People also ask

Can you cast an int to an enum?

You can explicitly type cast an int to a particular enum type, as shown below.

Can you cast an enum?

Enum's in . Net are integral types and therefore any valid integral value can be cast to an Enum type. This is still possible even when the value being cast is outside of the values defined for the given enumeration!

Can enums have numbers?

Numeric EnumNumeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.


1 Answers

From the documentation on enums in C# (MSDN)

A variable of type Day can be assigned any value in the range of the underlying type; the values are not limited to the named constants.

So the code certainly has no issue compiling. In addition:

Just as with any constant, all references to the individual values of an enum are converted to numeric literals at compile time. This can create potential versioning issues as described in Constants.

Assigning additional values to new versions of enums, or changing the values of the enum members in a new version, can cause problems for dependent source code.

You are actually taking advantage of this. Running on .NET 4.0 the framework doesn't know what to do with the 3072 value, but the .NET 4.5 framework does. You just don't have a convenient shortcut (the enum) to get to that value.

like image 171
BradleyDotNET Avatar answered Oct 17 '22 11:10

BradleyDotNET