dor
dor

Reputation: 105

c# add parameter for each methods in class

public class BaseDAL
{
    protected object GetOrder(int id)
    {
        using (var DB = AccessManager.db)
        {
            return DB.Videos.Where(x => x.ID == id).SingleOrDefault();
        }
    }

    public object GetByID(int id)
    {
        using (var DB = AccessManager.db)
        {
            return DB.Videos.Where(x => x.ID == id).SingleOrDefault();
        }
    }
}

Is there any option to add this param int id for any function in class without write it each function?

Somthing like:

public class BaseDAL : ADD SOME CODE THAT SHARE int id for all funcs
{
    protected object GetOrder()
    {
        using (var DB = AccessManager.db)
        {
            return DB.Videos.Where(x => x.ID == id).SingleOrDefault();
        }
    }

    public object GetByID()
    {
        using (var DB = AccessManager.db)
        {
            return DB.Videos.Where(x => x.ID == id).SingleOrDefault();
        }
    }
}

and GetOrder(12); will works. I want this done only to reduce the code.

Upvotes: 0

Views: 323

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 415705

You could set an ID parameter in the constructor, like so:

public class BaseDAL
{

    public BaseDAL(int ID)
    {
       this.id= ID;
    }

    int id;

    protected object GetOrder()
    {
        using (var DB = AccessManager.db)
        {
            return DB.Videos.Where(x => x.ID == id).SingleOrDefault();
        }
    }

    public object GetByID()
    {
        using (var DB = AccessManager.db)
        {
            return DB.Videos.Where(x => x.ID == id).SingleOrDefault();
        }
    }
}

That allows you to write code like this:

var result = new BaseDAL(5).GetOrder();

You could also combine this with the other answer, so that you have a property you can set and change. But I don't really think either is a good idea. I think what you already have is better. Also, I think you'd be better served to return Order and Video objects, rather than Objects.

Upvotes: 1

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112324

Add a CurrentIndex property to your class

public class BaseDAL
{
    public CurrentIndex { get; set; }

    public Order GetOrder()
    {
        using (var DB = AccessManager.db) {
            return DB.Videos.Where(x => x.ID == CurrentIndex).SingleOrDefault();
        }
    }

    ...
}

and use it like this

var dal = new BaseDAL();
dal.CurrentIndex = 5;
var result = dal.GetOrder();

Upvotes: 0

Related Questions