Shaul Behr
Shaul Behr

Reputation: 38003

Is it possible to make an anonymous class inherit another class?

This is a long shot, but I have a funny coding situation where I want the ability to create anonymous classes on the fly, yet be able to pass them as a parameter to a method that is expecting an interface or subclass. In other words, I'd like to be able to do something like this:

public class MyBase { ... }

public void Foo(MyBase something)
{
  ...
}

...
var q = db.SomeTable.Select(t =>
        new : MyBase // yeah, I know I can't do this...
        {
          t.Field1,
          t.Field2,
        });
foreach (var item in q)
  Foo(item);

Is there any way to do this other than using a named class?

Upvotes: 67

Views: 16871

Answers (4)

Anders
Anders

Reputation: 17554

Short answer: no

Long answer: You could use a C# proxy class. There are several tools that can proxy classes. For example Moqs. https://github.com/moq/moq4

Upvotes: 2

Shlomi Borovitz
Shlomi Borovitz

Reputation: 1700

No. From the documentation:

Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object.

To solve your problem, just replace the anonymous type with normal class...

Upvotes: 8

T McKeown
T McKeown

Reputation: 12847

Cannot extend an anonymous but you could declare your method to accept a dynamic parameter if you really need this to work.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500495

No. Anonymous types always implicitly derive from object, and never implement any interfaces.

From section 7.6.10.6 of the C# 5 specificiation:

An anonymous object initializer declares an anonymous type and returns an instance of that type. An anonymous type is a nameless class type that inherits directly from object.

So if you want a different base class or you want to implement an interface, you need a named type.

Upvotes: 65

Related Questions