1
if(new DateTime() == default(DateTime))
{
  //blah blah...
}

Code 'new DateTime()' will create new instance and take some memory for itself.

I want to know is Code 'default(DateTime)' also create new instance and take some memory or just compare and then end

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
JY Lee
  • 45
  • 6
  • for a value type it calls CIL `initobj` which Initializes each field of the value type at a specified address to a null reference or a 0 of the appropriate primitive type and pushes it onto the stack, yeet... Does it use memory? yes, can you run out of stack memory? yes. should you worry about this, probably not in your example . – TheGeneral Jun 18 '20 at 06:04
  • @SelimYıldız This question is just 'default(DateTime)' allocate some memory, not 'default(DateTime) == new DateTime' is true or false. Thank you – JY Lee Jun 18 '20 at 06:09
  • 1
    Did you check the answer of that question https://stackoverflow.com/a/13957724/5519709? I think this can be answer your question as well which says `default(), for any value type (DateTime is a value type) will always call the parameterless constructor.` – Selim Yildiz Jun 18 '20 at 06:12
  • @SelimYıldız OK, i got it – JY Lee Jun 18 '20 at 06:15
  • 1
    @Selim um... C# *hardly ever* (I want to say "never", but I can't be bothered to use ilasm to write a value-type with an explicit parameterless constructor, to see what it does) "calls a parameterless constructor" for value-types - usually, it uses the `initobj` IL instruction - and it certainly does for `DateTime` – Marc Gravell Jun 18 '20 at 06:18
  • `DateTime` is a value type. There is no memory allocation here. – Jeremy Lakeman Jan 11 '23 at 05:49

2 Answers2

1

For value types, it sets to zero, e.g. default int is 0. For reference types default is null.

See the docs for details.

Since DateTime is a value type, it will be allocated on the stack, rather than the heap. It will only take up memory inside the current stack frame, or if it is a member of a class.

BigDave
  • 21
  • 3
1

As stated here, it creates a new default value. So its same memory allocation as it happens for value type and reference type. First one on stack second on heap

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/default#default-literal

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197