Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extend a class to conform to an interface?

I have an interface:

interface IFoo {
  int foo(int bar);
}

Can I now extend an existing class to conform to the interface? Say class String. I know I can define the foo() method on strings. But is it possible to go further and tell the compiler that strings can be cast to IFoo?

like image 983
William Jockusch Avatar asked Oct 13 '13 02:10

William Jockusch


1 Answers

You can do it with other classes, but not with System.String, because it is sealed.

If you wanted to do this to a non-sealed class, you could simply derive from it, add appropriate constructors, and put the interface as something that your new class implements.

interface IFoo {
    int Size {get;}
}
// This class already does what you need, but does not implement
// your interface of interest
class OldClass {
    int Size {get;private set;}
    public OldClass(int size) { Size = size; }
}
// Derive from the existing class, and implement the interface
class NewClass : OldClass, IFoo {
    public NewCLass(int size) : base(size) {}
}

When the class is sealed, your only solution of presenting it as some interface through composition: write a wrapper class implementing your interface, give it an instance of the sealed class, and write method implementations that "forward" calls to the wrapped instance of the target class.

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

Sergey Kalinichenko