Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic and non-generic interfaces

Tags:

c#

generics

I come across a lot of situations where I have declared a generic interface and later I needed a non-generic version of this interface, or at least non-generic version of some of the methods or properties on that interface. I would usually declare a new non-generic interface and have it inherit the generic interface. The problem I am running into in shows in the example below:

public abstract class FormatBase { }

public interface IBook<F> where F : FormatBase
{
    F GetFormat();
}

public interface IBook
{
    object GetFormat();
}

public abstract class BookBase : IBook<FormatBase>, IBook
{
    public abstract FormatBase GetFormat();

    object IBook.GetFormat()
    {
        return GetFormat();
    }
}

Since the only way to declare the IBook (non-generic) interface is explicitly, how do you guys go about making it abstract?

like image 591
BlueChameleon Avatar asked Jul 13 '12 15:07

BlueChameleon


1 Answers

Just delegate:

public abstract class BookBase : IBook<FormatBase> {
  public abstract FormatBase GetFormat();

  object IBook.GetFormat() {
    return GetFormat();
  }
}

Or, if you still want to differentiate both methods, delegate to a new method:

public abstract class BookBase : IBook<FormatBase> {
  public abstract FormatBase GetFormat();

  public abstract object IBook_GetFormat();

  object IBook.GetFormat() {
    return IBook_GetFormat();
  }
}

You also need new to dodge a "hiding inherited member" warning:

public interface IBook<F> : IBook 
where F : FormatBase {
  new F GetFormat();
}

Also, it might make more sense to let concrete classes decide on the concrete FormatBase:

public abstract class BookBase<F> : IBook<F> 
where F : FormatBase {
  public abstract F GetFormat();

  object IBook.GetFormat() {
    return GetFormat();
  }
}
like image 95
Jordão Avatar answered Oct 12 '22 22:10

Jordão