Please tell us what is the default keyword in C # .net

I have the following code:

I have an enumeration:

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

and m using this listing as follows:

 HardwareInterfaceType type = default(HardwareInterfaceType);

please tell me what does the keyword "default" do here? what is its use?

+5
source share
4 answers

I believe the default value is 0, so you will have an invalid HardwareInterfaceType file. I personally do not like this kind of coding for listings. IMO it is more clear to define the value of Enum as "Undefined" or "None" and then initialize the variable instead.

"Gotchas" , , . , Enum, . , IMO .

var foobar = default(HardwareInterfaceType);
Console.WriteLine(Enum.IsDefined(typeof(HardwareInterfaceType), foobar)); //returns false
Console.WriteLine(foobar); //returns 0
+7

default - , - . null.

, .

+5

.

: T, , T , T - , .

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
+4

I think the Default keyword is used when you don't need to create a new instance of any class object, say:

one way is like this

HardwareInterfaceType type = new HardwareInterfaceType();

and the second way is similar to this

HardwareInterfaceType type = default(HardwareInterfaceType);

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

+2
source

All Articles