10

I know that you can't have a constructor in an interface, but here is what I want to do:

 interface ISomething 
 {
       void FillWithDataRow(DataRow)
 }


 class FooClass<T> where T : ISomething , new()
 {
      void BarMethod(DataRow row)
      {
           T t = new T()
           t.FillWithDataRow(row);
      }
  }

I would really like to replace ISomething's FillWithDataRow method with a constructor somehow.

That way, my member class could implement the interface and still be readonly (it can't with the FillWithDataRow method).

Does anyone have a pattern that will do what I want?

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
Toto
  • 7,491
  • 18
  • 50
  • 72

2 Answers2

9

use an abstract class instead?

you can also have your abstract class implement an interface if you want...

interface IFillable<T> {
    void FillWith(T);
}

abstract class FooClass : IFillable<DataRow> {
    public void FooClass(DataRow row){
        FillWith(row);
    }

    protected void FillWith(DataRow row);
}
NDM
  • 6,731
  • 3
  • 39
  • 52
7

(I should have checked first, but I'm tired - this is mostly a duplicate.)

Either have a factory interface, or pass a Func<DataRow, T> into your constructor. (They're mostly equivalent, really. The interface is probably better for Dependency Injection whereas the delegate is less fussy.)

For example:

interface ISomething 
{      
    // Normal stuff - I assume you still need the interface
}

class Something : ISomething
{
    internal Something(DataRow row)
    {
       // ...
    }         
}

class FooClass<T> where T : ISomething , new()
{
    private readonly Func<DataRow, T> factory;

    internal FooClass(Func<DataRow, T> factory)
    {
        this.factory = factory;
    }

     void BarMethod(DataRow row)
     {
          T t = factory(row);
     }
 }

 ...

 FooClass<Something> x = new FooClass<Something>(row => new Something(row));
Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194