I have got following code:
I have a enum:
public enum HardwareInterfaceType
{
Gpib = 1,
Vxi = 2,
GpibVxi = 3,
}
and m using this enum like this :
HardwareInterfaceType type = default(HardwareInterfaceType);
please tell me what is keyword "default" is doing here? what is the use of it?
The default statement is executed if no case constant-expression value is equal to the value of expression . If there's no default statement, and no case match is found, none of the statements in the switch body get executed. There can be at most one default statement.
The default keyword specifies some code to run if there is no case match in the switch. Note: if the default keyword is used as the last statement in a switch block, it does not need a break .
if, else, switch, case, default – Used for decision control programming structure. break – Used with any loop OR switch case. int, float, char, double, long – These are the data types and used during variable declaration.
The default keyword is introduced in C ++ 11. Its use tells the compiler to independently generate the corresponding class function, if one is not declared in the class. As you know, the compiler automatically generates a number of class constructors and a destructor.
I believe the default is 0, so you will have an invalid HardwareInterfaceType generated. I personally don't like this sort of coding for enums. IMO it's more clear to define an Enum value of "Undefined" or "None" and then initialize the variable to that instead.
One of the "Gotchas" with enums is that they can be initialized to a value that does not exist in the enum. The original programmer might have thought that the enum would be initialized to some valid value in the Enum definition if he used the "default" keyword. Not true, and IMO this is not a good use of the "default" keyword at all.
var foobar = default(HardwareInterfaceType);
Console.WriteLine(Enum.IsDefined(typeof(HardwareInterfaceType), foobar)); //returns false
Console.WriteLine(foobar); //returns 0
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