Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 495
Shaul Behr Avatar asked Mar 06 '14 14:03

Shaul Behr


People also ask

Can Anonymous classes extend other classes?

Since they have no name, we can't extend them. For the same reason, anonymous classes cannot have explicitly declared constructors.

Can an anonymous class be declared as implementing an interface and extending a class?

A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time. A regular class can extend a class and implement any number of interfaces simultaneously. But anonymous Inner class can extend a class or can implement an interface but not both at a time.

Can anonymous class have constructor?

Since anonymous inner class has no name, an anonymous inner class cannot have an explicit constructor in Java.

Can a class inherit from an inherited class?

Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.


Video Answer


2 Answers

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.

like image 96
Jon Skeet Avatar answered Sep 23 '22 02:09

Jon Skeet


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...

like image 40
Shlomi Borovitz Avatar answered Sep 25 '22 02:09

Shlomi Borovitz