Friday, February 11, 2011

C# Abstract class, using anonymous instead of declaring concrete class?

I have an abstract class and I would like to use it quickly by NOT create a concrete class that inherit the abstract class. Well, to define the abstract method anonymously.

Something like that:

           Command c = new Command(myObject){
               public override void Do()
               {
               }                   
            };

Is it possible in C# .net 2.0?

  • You could create a type that wraps an action providing an implementation as such:

    class ActionCommand
    {
        private readonly Action _action;
    
        public ActionCommand(Action action)
        {
            _action = action;
        }
    
        public override void Do()
        {
            _action();
        }                   
    };
    

    This then can be used as so:

    Command c = new Command((Action)delegate()
               {
                  // insert code here
               });
    

0 comments:

Post a Comment