DooDoo
DooDoo

Reputation: 13487

Return type from generic methods

I'm Sorry again but this question continuance of my first question: consider this Interface:

 interface IRepository<T,U> where T:class where U:class 
{
    IEnumerable<U> SelectAll();

    bool Insert(T item);

    IEnumerable<T> FindAll(Func<T, bool> exp);
}

and I Implement this interface:

 public class Repository : IRepository<Customer,Select4ColumnsOfCustomers>
{

    #region IRepository<Customer,Select4ColumnsOfCustomers> Members

    public IEnumerable<Select4ColumnsOfCustomers> SelectAll()
    {
        throw new NotImplementedException();
    }

    public bool Insert(Customer item)
    {
        throw new NotImplementedException();
    }

    public IEnumerable<Customer> FindAll(Func<Customer, bool> exp)
    {
        throw new NotImplementedException();
    }

    #endregion
}

public class Select4ColumnsOfCustomers
{
    public int CustomerID { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Phone { get; set; }
}

I want to return just 4 column of Customer table in northwind database. Ok.this work but if I want to add other method that return other types I must declare S,U,M,W,... in Interface and in Implement of it I must write this Code:

public class Repository : IRepository<Customer,RetType1,RetType2,RetType3,....>

this not good.what is alternative for this.Is it possible that write var for Return Types?Or a place holder for return types? thanks

Upvotes: 1

Views: 643

Answers (1)

Vadim
Vadim

Reputation: 17955

Your repository can implement multiple interfaces.

public class Repository : IRepository<TResult1, T1>, IRepository<Tresult2, T2>, etc...

Your SelectAll method will need to be generic like

TResult SelectAll<TResult>();

However Andrzej is right, consider using an ORM so that you can generalize this code. Check out NHiberante and Entity Framework.

Upvotes: 3

Related Questions