58

First of all i searched on this and i found the following links on Stack Overflow:

But i'm not satisfied with this answer, it's not explained well (i didn't get it well). Basically, i want to know the difference between new object() and new {}. How, they are treated at compile time and runtime?

Secondaly, i have the following code which i have used for WebMethods in my asp.net simple application

[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static object SaveMenus(MenuManager proParams)
{
    object data = new { }; // here im creating an instance of an 'object' and i have typed it `new {}` but not `new object(){}`.
    try
    {
        MenuManager menu = new MenuManager();    
        menu.Name = proParams.Name;
        menu.Icon = proParams.Icon;
        bool status = menu.MenuSave(menu);
        if (status)
        {
            // however, here i'm returning an anonymous type
            data = new
            {
                status = true,
                message = "Successfully Done!"
            };
        }
    }
    catch (Exception ex)
    {
        data = new { status = false, message = ex.Message.ToString() };
    }
    return data;
}

So, (as you can see in comments in code), How new object(){} and new {} differences?

Is this even the right way that i have write the code? Can you suggest a best way for this code?

I know, i can't explain it well and i'm asking alot, but that's the best i have right now.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Idrees Khan
  • 7,702
  • 18
  • 63
  • 111
  • 7
    Your `new{}` is creating an [anonymous type](http://msdn.microsoft.com/en-us/library/vstudio/bb397696.aspx) – CodesInChaos Jul 11 '13 at 06:34
  • 4
    new {} is for anonymous type and new object() is just the constructor of the object class. – Cybermaxs Jul 11 '13 at 06:34
  • 1
    @Cybermaxs-Betclic, i know the result type is an anonymous type of an object but how they are treated by `MSIL` ? Will this generate a new `Anonymouse` type separate code by c# compliler? – Idrees Khan Jul 11 '13 at 06:40
  • 1
    That was new info to me. Can I use `new {}` to create instance for all objects types? – Subin Jacob Jul 11 '13 at 06:47
  • Note that if you declared it `var a = new { };` and `var o = new object();`, then there is one difference, former is assignable only to another similar anonymous object, while latter being object, it can be assigned to anything. – nawfal Sep 07 '14 at 10:46

3 Answers3

64

new {...} always creates an anonymous object, for instance:

  Object sample = new {};
  String sampleName = sample.GetType().Name; // <- something like "<>f__AnonymousType0" 
                                             //                    not "Object"

while new Object() creates an instance of Object class

  Object sample = new Object() {};
  String sampleName = sample.GetType().Name; // <- "Object"

since all objects (including anonymous ones) are derived from Object you can always type

  Object sample = new {};
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • much better explanation. so, it means, they are treated as an `object` type at runtime and compiler doesn't treat it as `anonymous` type – Idrees Khan Jul 11 '13 at 06:47
  • 5
    @DotNetDreamer What do you mean "they are treated as an object type at runtime"? All objects inherit from the `Object` class, but Dimitry's example specifically shows that the anonymous object's actual type is _not_ Object. – JLRishe Jul 11 '13 at 07:02
13

To see the difference between new Object() and new {} and new Object(){}... why don't we just find out?

Console.WriteLine(new Object().GetType().ToString());
Console.WriteLine(new Object() { }.GetType().ToString());
Console.WriteLine(new { }.GetType().ToString());

The first two are just different ways of creating an Object and prints System.Object. The third is actually an anonymous type and prints <>f__AnonymousType0.

I think you might be getting confused by the different uses of '{}'. Off the top of my head it can be used for:

  1. Statement blocks.
  2. Object/Collection/Array initialisers.
  3. Anonymous Types

So, in short object data = new { }; does not create a new object. It creates a new AnonymousType which, like all classes, structures, enumerations, and delegates inherits Object and therefor can be assigned to it.


As mentioned in comments, when returning anonymous types you still have declare and downcast them to Object. However, they are still different things and have some implementation differences for example:

static void Main(string[] args)
{
    Console.WriteLine(ReturnO(true).ToString());  //"{ }"
    Console.WriteLine(ReturnO(false).ToString());  // "System.Object"

    Console.WriteLine(ReturnO(true).Equals(ReturnO(true)));  //True
    Console.WriteLine(ReturnO(false).Equals(ReturnO(false)));  //False
    Console.WriteLine(ReturnO(false).Equals(ReturnO(true)));  //False

    Console.WriteLine(ReturnO(true).GetHashCode());  //0
    Console.WriteLine(ReturnO(false).GetHashCode());  //37121646

    Console.ReadLine();
}

static object ReturnO(bool anonymous)
{
    if (anonymous) return new { };
    return new object();
}
NPSF3000
  • 2,421
  • 15
  • 20
  • what will be the return of my `webmethod` an `anonymouse` or `object` type ? – Idrees Khan Jul 11 '13 at 07:08
  • 1
    The return type is object - you can't return anonymous type because... you don't actually know what the type is at compile time. However returning an anonymous type (downcast to an object) and returning an object may lead to different behaviour - e.g. they implement ToString() differently. – NPSF3000 Jul 11 '13 at 07:10
  • 1
    thank your for the new info. i wish i had more then +1 for you :) – Idrees Khan Jul 11 '13 at 07:11
8

new{ } creates an instance of an anonymous type with no members. This is different from creating an instance of object. But like almost all types, anonymous types can be assigned to object.

 object data = new { };
 Console.WriteLine(data.GetType().Name)

Clearly shows an auto-generated name, not Object.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262