How to implement interface in anonymous class in C#?


No, anonymous types cannot implement an interface. We need to create your own type.

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.

The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.

You create anonymous types by using the new operator together with an object initializer.

Example

class Program{
   public static void Main(){
      var v = new { Amount = 108, Message = "Test" };
      Console.WriteLine(v.Amount + v.Message);
      Console.ReadLine();
   }
}

Output

108Test

Updated on: 19-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements