What is the Difference Between `new object()` and `new {}` in C#?

56,455

Solution 1

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 {};

Solution 2

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();
}

Solution 3

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.

Share:
56,455
Idrees Khan
Author by

Idrees Khan

Well, in short. I love working with new technologies in Web, Mobile and Desktop. Techs such Angular, React, .Net, Xamarin, Ionic, Angular, Node are the one i am mostly targeting. I love building new things (of course not buildings) and i am very passionate by playing with many .js frameworks.

Updated on July 09, 2022

Comments

  • Idrees Khan
    Idrees Khan almost 2 years

    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.

  • p.s.w.g
    p.s.w.g almost 11 years
    "like almost all types, anonymous types can be assigned to object" can you name one that can't?
  • CodesInChaos
    CodesInChaos almost 11 years
    Obvious example are pointers. I think there are some more, stuff like those weird argument iterators or certain kinds of references that can't be used in C# directly.
  • Mare Infinitus
    Mare Infinitus almost 11 years
    pointer in c#, so unsafe... but everything in the "safe" part.
  • p.s.w.g
    p.s.w.g almost 11 years
    @CodesInChaos I see. Thanks for the info.
  • Idrees Khan
    Idrees Khan almost 11 years
    much better explanation. so, it means, they are treated as an object type at runtime and compiler doesn't treat it as anonymous type
  • JLRishe
    JLRishe almost 11 years
    @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.
  • Idrees Khan
    Idrees Khan almost 11 years
    what will be the return of my webmethod an anonymouse or object type ?
  • NPSF3000
    NPSF3000 almost 11 years
    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.
  • Idrees Khan
    Idrees Khan almost 11 years
    thank your for the new info. i wish i had more then +1 for you :)