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.
You can explicitly type cast an int to a particular enum type, as shown below.
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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With