5

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

3 Answers 3

8

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.

2

You can achieve something very similar through clever use of lambdas:

public class BaseClass {

    public BaseClass(Action<string> abs1 = null, Action<string> abs2 = null){
       AbstractMethod1 = abs1 ?? s=>{};
       AbstractMethod2 = abs2 ?? s=>{};
    }

    public Action<string> AbstractMethod1 {get; private set;}
    public Action<string> AbstractMethod2 {get; private set;}
}

So you could use this definition like so:

new BaseClass( s=> Console.WriteLine(s), s=> Console.WriteLine(s));

You could also define all the methods as part of an interface and then construct a class with a concrete implementation of the interface (proxying the calls to the concrete implementation) -- I would call that the "Strategy" Pattern. But that's just a variation of this theme.

4
  • This is nice, but not something someone just learning C# should think about :)
    – TDaver
    May 27, 2012 at 20:34
  • @TDaver, lambda expressions have been part of .net for more than 4 years, they're everywhere. The author is familiar with Java, which has a lambdas, so it's not a new concept, just a slightly different (better?) syntax. May 27, 2012 at 20:40
  • while I agree with you that lambdas are good and should be used (especially with LINQ), but a beginner has a hard time to actually grasp the class design considerations of a base class like the one you're suggesting :)
    – TDaver
    May 27, 2012 at 20:45
  • and being in use for a long time means nothing for a beginner. yield return has been around longer and I still cannot teach it to less advanced users without some headache :)
    – TDaver
    May 27, 2012 at 20:46
0

Don't know Java, but this "smells" like Anonymous Types in C#.

For example, you can write something like:

 var myNewType = new { 
                       Name = "Charles", 
                       Surname="Dickens", 
                       Age = 55 
                      };
1
  • 1
    No, doesn't have much in common with anonymous classes - even if they sound similar.
    – Voo
    May 27, 2012 at 20:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.