Search code examples
c#initializationvalue-type

In which scenarios would you initialize a value type with a new keyword?


My question is about using new for a value type (int, bool,...)

int i = new int();

in this case i is initialized with a value zero.

I have read that it's not a good thing to use new with the value types and does not, however, dynamically allocate memory(just on stack). So the questions is why the C# Compiler makers have let us to do so, in which situation this method comes handy?


Solution

  • I have read that it's not a good thing to use new with the value types and does not, however, dynamically allocate memory(just on stack). So the questions is why the C# Compiler makers have let us to do so, in which situation this method comes handy?

    There is at least one reason for this:

    void MyFunc<T>() where T : new()
    {
        T someValue = new T();
        // probably other code here :-)
    }
    

    call it with

    MyFunc<int>();
    

    With generics you must be able to use the new(). if some value types didn't have the new() then it would be impossible to write code like that.

    Note that for int, long, ... and nearly all the other primitive value types (except bool, and for bool there is the new bool() == false) you can use numeric literals to initialize them (0, 1, ...), but for other value types you can't. You have to use static values (that are then built in some other ways) or the new operator. For example DateTime :-)

    You can't write:

    DateTime dt = 0;
    

    You have to write:

    DateTime dt = DateTime.MinValue; // Where DateTime.MinValue is probably defined as new DateTime()
    

    or

    DateTime dt = new DateTime();
    

    or

    DateTime dt = new DateTime(2015, 02, 28);
    

    or (as written by Henk Holterman)

    DateTime dt = default(DateTime);
    

    (note that you can even write int x = default(int) :-) )