Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any use to instantiating an enum with new?

Tags:

c#

People also ask

Can we instantiate an enum type using the new operator?

We cannot instantiate an enum type using the new operator. An enum type is implicitly final. Enum types inherit members from the Object class, as any other reference type.

Can we create object for enum?

The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Can we create instance of enum in Java?

10) You can not create an instance of enums by using a new operator in Java because the constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself. 11) An instance of Enum in Java is created when any Enum constants are first called or referenced in code.

Can we add new enumeration value by runtime?

No, it can't as this would mean that you would be able to modify existing types at runtime which you can't.


new T(), when T is a value type, is not a boxing operation. It is the same thing as default(T). Foo x = new Foo();, Foo x = default(Foo), and Foo x = Foo.Bar; all do exactly the same thing.

Reference:

Initializing Value Types

int myInt = new int();

–or–

int myInt = 0;

Using the new operator calls the default constructor of the specific type and assigns the default value to the variable. In the preceding example, the default constructor assigned the value 0 to myInt. For more information about values assigned by calling default constructors, see Default Values Table.


At an IL level there is no difference between Foo.Bar and new Foo(). Both will evaluate to the same set of IL opcodes

L_0001: ldc.i4.0 
L_0002: stloc.0 

The only case these operations translate into different IL is when the new operation is done generically

void Method<T>() where T : struct {
  T local = new T();
}

Method<Foo>();

In this particular case new will produce a different set of op codes

L_0005: ldloca.s e3
L_0007: initobj !!T

Other than this somewhat esoteric difference, there is no practical difference between Foo.Bar and new Foo()


See MSDN's entry on the System.Enum Class, particularly the section labeled Instantiating an Enumeration Type.

From what I understand, creating an instance of an Enum gives you the default value for that Enum (which is 0).

Example (taken directly from the MSDN article):

public class Example
{
   public enum ArrivalStatus { Late=-1, OnTime=0, Early=1 };
   public static void Main()
   {
      ArrivalStatus status1 = new ArrivalStatus();
      Console.WriteLine("Arrival Status: {0} ({0:D})", status1);
   }
}
// The example displays the following output: 
//       Arrival Status: OnTime (0)