tags:

views:

201

answers:

4

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?

+4  A: 

default keyword is mainly used while writing generic code.

In generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T when you do not know if T will be a reference type or a value type and If T is a value type, whether it will be a numeric value or a struct.

In your case it assigns 0.

    static void Main(string[] args)
    {

        HardwareInterfaceType type = default(HardwareInterfaceType);
        Console.WriteLine(type.ToString());

        type = HardwareInterfaceType.Gpib;
        Console.WriteLine(type.ToString());

        Console.ReadLine();
    }

    public enum HardwareInterfaceType
    {
        Gpib = 1,
        Vxi = 2,
        GpibVxi = 3,
    }

    //output
    0
    Gpib
this. __curious_geek
in my case what is it assigning?
Rajesh Rolen- DotNet Developer
In your case it assigns 0.
this. __curious_geek
+4  A: 

default will supply the default value for a language type - in the case of numeric values, and by extension, enumerations, zero. for reference types, the default would be null.

It's more commonly used with generics where the type isn't known up front.

Rowland Shaw
+6  A: 

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
Dave Markle
+1 for the "Undefined"-value
Christian
+2  A: 

I think the Default key word is used when you don't have to create new instance of any class object say:

one way is like this

HardwareInterfaceType type = new HardwareInterfaceType();

and second way is like this also

HardwareInterfaceType type = default(HardwareInterfaceType);

The above code will create object of hardwareinterfacetype but it will not create any new memory.

J S Jodha