SerenityNow
SerenityNow

Reputation: 1065

how to specify optional anonymous ienumerable parameters in c# abstract method

I have the following base class

public abstract class BaseRepository<T>
{
    public abstract IEnumerable<T> GetAll();
}

And a class the inherits it.

public class CustomerRepository: BaseRepository<Customer>
{
    public override IEnumerable<Customer>GetAll()
    {
        return null;
    }
}


public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

what i want to do is using this class

public class Sales
{
    public int Id { get; set; }
    public int CustomerId {get;set;}
    public decimal Total {get;set;}
}

this doesn't work

public class SalesRepository: BaseRepository<Sales>
{
    public override IEnumerable<Sales>GetAll(IEnumerable<Customer> Customers)
    {
        return null;
    }
}

My question is, how to I modify my BaseClass to have optional ienumerable parameters of that i can then use as needed.

Upvotes: 0

Views: 317

Answers (3)

CSJ
CSJ

Reputation: 3941

The GetAll(IEnumerable<Customer> Customers) function amounts to a new method. It does not have the same signature of the base, and so cannot be overridden in this way. The SalesRepository class, if it is to be a BaseRepository<Sales>, must implement the GetAll() method as is.

Upvotes: 4

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

You can do this change

public class SalesRepository : BaseRepository<Sales>
{
    public override IEnumerable<Sales> GetAll()
    {
        return GetAll(null);
    }

    public IEnumerable<Sales> GetAll(IEnumerable<Customer> Customers)
    {
        return null;
    }
}

BaseRepository<Sales> rep = new SalesRepository();
rep.GetAll();

this will call overridden version and makes a call to GetAll(null). To pass value to GetAll() method you need to have do the following

SalesRepository srep = new SalesRepository();
srep.GetAll(new Customer[] { new Customer() });

Upvotes: 1

BlargleMonster
BlargleMonster

Reputation: 1622

You can either mark parameter as optional or you can make overloads to the method in your base class, both of which will result in the same thing. When you mark a parameter as optional the compiler simply makes the overloads for you.

Ultimately you probably need to make two methods in your base class and then either hide one (make private) in your implementation of each parent class or have it throw an error. If you can figure out a good way to have default values then that may work as well.

Upvotes: 1

Related Questions