6

in c#,

var x = new {};

declares an anonymous type with no properties. Is this any different from

var x = new object();

?

Gabe Moothart
  • 31,211
  • 14
  • 77
  • 99
  • Does this answer your question? [What is the Difference Between \`new object()\` and \`new {}\` in C#?](https://stackoverflow.com/questions/17586525/what-is-the-difference-between-new-object-and-new-in-c) – ggorlen Mar 18 '20 at 03:14

4 Answers4

10

Yes, the types used are different. You can tell this at compile-time:

var x = new {};
// Won't compile - no implicit conversion from object to the anonymous type
x = new object(); 

If you're asking whether new{} is ever useful - well, that's a different matter... I can't immediately think of any sensible uses for it.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • "whether new{} is ever useful" this is a good material for another question. :) – Arnis Lapsa Jun 22 '09 at 16:10
  • I'm curious, does the anonymous object created by new {} still inherit from System.Object? – Patrick McDonald Jun 22 '09 at 16:13
  • 1
    All C# types inherit from System.Object, so yes. – Timothy Carter Jun 22 '09 at 16:15
  • 4
    Strictly speaking, all C# class and struct types inherit from (or are identical to) object. Interface types are convertible to object but do not inherit from object. Type parameter types are convertible to their effective base class, which always inherits from (or is identical to) object. Pointer types neither inherit from nor are convertible to object. – Eric Lippert Jun 22 '09 at 16:37
  • `new{}` is great: it's far more compact than `new object()`. – yfeldblum Jun 22 '09 at 16:40
8

Well, for starters, object is an actual, non-anonymous type...if you do x.GetType() on the 2nd example, you'll get back System.Object.

Jonas
  • 4,454
  • 3
  • 37
  • 45
0

Along with the return from GetType as mentioned, x would not be of type object, so you would not be able to assign an object type to that variable.

        var x = new { };
        var y = new object();

        //x = y; //not allowed
        y = x; //allowed
Timothy Carter
  • 15,459
  • 7
  • 44
  • 62
0

Jon Skeet's answer was mostly what I wanted, but for the sake of completeness here are some more differences, gained from reflector:

new {} overrides three methods of object :

  1. Equals - as mentioned in other answers, new object and new {} have different types, so they are not equal.
  2. GetHashCode returns 0 for new {} (but why would you put it in a hash table anyway?)
  3. ToString prints "{}" for new {}

Unfortunately I can't think of a practical application for all this. I was just curious.

Gabe Moothart
  • 31,211
  • 14
  • 77
  • 99