开发者

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

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 us开发者_JAVA百科e of it?


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


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜