views:

190

answers:

3

Hello,

I know that we can't have 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);
          }
      }

It would be better replacing the method FillWithDataRow in ISomething definition by a contructor.

Indeed, now my member class can be readonly (they can't with the current method).

Anyone has some patterns in order to do what I want ?

+5  A: 

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);
}
Nicky De Maeyer
+3  A: 

(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));
Jon Skeet
A: 

Abstract base class using with a constructor that takes a DataRow, and does the work of FillWithDataRow ?

NeilDurant