Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override abstract method upon instance creation in c#

Tags:

java

c#

.net

In java, we can override or implement abstract methods upon instance creation as follows:

AbstractClass test =new AbstractClass() 
{
    public void AbstractMethod(string i) {

    }
    public void AbstractMethod2(string i) {

    }
};

Is this possible in C#? if Yes, what's the equivalent code

Thanks

like image 215
PyQL Avatar asked May 27 '12 20:05

PyQL


People also ask

Can you override an abstract method?

A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.

Is it mandatory to override abstract method in derived class C#?

When the derived class inherits the abstract method from the abstract class, it must override the abstract method. This requirment is enforced at compile time and is also called dynamic polymorphism.

Is it mandatory to override abstract method in derived class?

It is necessary to override all the methods which are declared as abstract . you cannot skip the non-concrete methods. If you really want to do then make your class as abstract. you cannot change the mechanism of abstraction.

Can a class override a method and declare it to be abstract?

This is because every child class must override these methods and provide an implementation of them. Thus we can declare these methods as abstract in the parent class.


1 Answers

This Java feature is called "anonymous class", not "an override of method on instance creation". There is no identical feature in C#.

C# took a different route - instead of providing convenience syntax for creation of subclasses, it expanded upon its delegate features, providing anonymous delegates and lambdas. Lambdas let you plug in pieces of code.

like image 64
Sergey Kalinichenko Avatar answered Sep 21 '22 01:09

Sergey Kalinichenko