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

前端 未结 3 1027
温柔的废话
温柔的废话 2020-12-24 04:43

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

  • Is there any difference between `new object()` and `new {}` in c#?
3条回答
  •  佛祖请我去吃肉
    2020-12-24 05:32

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

提交回复
热议问题