Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Syntax
Following is the syntax for creating anonymous types −
var anonymousObject = new { Property1 = value1, Property2 = value2 };
Why Anonymous Types Cannot Implement Interfaces
Anonymous types are compiler-generated classes that derive directly from Object. Since interface implementation requires explicit type definitions with method implementations, anonymous types cannot implement interfaces. They can only contain auto-implemented properties.
Using Anonymous Types
Example
using System;
class Program {
public static void Main() {
var v = new { Amount = 108, Message = "Test" };
Console.WriteLine(v.Amount + v.Message);
var person = new { Name = "John", Age = 30, City = "New York" };
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, City: {person.City}");
}
}
The output of the above code is −
108Test Name: John, Age: 30, City: New York
Alternative: Using Named Classes with Interfaces
Since anonymous types cannot implement interfaces, you must create named classes when interface implementation is required −
Example
using System;
interface IPerson {
string GetFullInfo();
}
class Person : IPerson {
public string Name { get; set; }
public int Age { get; set; }
public string GetFullInfo() {
return $"Name: {Name}, Age: {Age}";
}
}
class Program {
public static void Main() {
IPerson person = new Person { Name = "Alice", Age = 25 };
Console.WriteLine(person.GetFullInfo());
// This would NOT work with anonymous types:
// IPerson anonymousPerson = new { Name = "Bob", Age = 30 }; // Compile error
}
}
The output of the above code is −
Name: Alice, Age: 25
Anonymous Types Limitations
| Feature | Anonymous Types | Named Classes |
|---|---|---|
| Interface Implementation | ? Not Supported | ? Supported |
| Custom Methods | ? Not Supported | ? Supported |
| Property Mutability | ? Read-only | ? Read/Write |
| Inheritance | ? Not Supported | ? Supported |
Conclusion
Anonymous types in C# cannot implement interfaces because they are compiler-generated classes with limited functionality. When you need interface implementation, you must create named classes that explicitly implement the required interface methods and properties.
