William Jockusch
William Jockusch

Reputation: 27335

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?

Upvotes: 8

Views: 4300

Answers (2)

philologon
philologon

Reputation: 2105

I think the question could be restated as, 'can I use extension methods to make a sealed class implement an interface that it did not before?' As others point out, the String class is sealed. However, I think you have to name what interfaces a class implements in its declaration:

public someClass : IFoo
{
    // code goes here
}

So you can't do this directly to String, not just because it is sealed, but because you do not have the source code for it.

The best you can do is make your own class that has-a String and use it like a string. Anything that a String does that you need to do you will either have to do on its String member (thus making it public), or you will have to wrap/reimplement the method you need:

public class betterString : IFoo
{
   public String str {get; set;}

   public foo(int i)
   {
      // implement foo
   }
}

then later, when using it:

public void someMethod(betterString better)
{
   better.foo(77);
   System.Console.WriteLine(better.str);
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

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.

Upvotes: 11

Related Questions