Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please tell me what is use of "default" keyword in c#.net

Tags:

c#

default

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?

like image 754
Dr. Rajesh Rolen Avatar asked May 25 '10 11:05

Dr. Rajesh Rolen


People also ask

What is the use of default in C?

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.

What is the use of default keyword?

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 .

Is default a keyword in C?

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.

What is the purpose of default keyword in C++ *?

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.


1 Answers

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
like image 179
Dave Markle Avatar answered Nov 10 '22 05:11

Dave Markle