Alex
Alex

Reputation: 77349

Reference generic property in expression

Let's say I have two Tables, Lunch and Dinner. I know that both contain the DateTime property "Time".

If I have a generic method GetTime, how could I return db.Lunch.Time when T is Lunch and db.Dinner.Time when T is Dinner? I'm trying to achieve this without testing for T individually using typeof, but rather generically.

Pseudocode:

public T GetTime<T>(DateTime dt)
{
    return MyDataContext.GetTable<T>().Where(entity => entity.Time == dt);
}

So when I call GetTime<Dinner> it will automatically look in the Dinner Table for all dinner entities with the property time equal to my supplied parameter dt.

The problem is that I can't specifiy entity.Time in my expression because T is a generic. My question is how to get around that, so that I can look for any T (knowing that all my entities in fact have the Time property) without having to create specific methods for Dinner and Lunch.

Upvotes: 1

Views: 386

Answers (3)

CSharpAtl
CSharpAtl

Reputation: 7512

You could use an interface that Lunch and Dinner implement that has a property called Time

 public interface IMealTime
    {
        DateTime Time { get; set; }
    }

    public class Lunch : IMealTime
    {
        #region IMealTime Members

        public DateTime Time { get; set; }

        #endregion
    }

    public class Dinner : IMealTime
    {
        #region IMealTime Members
        public DateTime Time { get; set; }

        #endregion
    }

    public class GenericMeal
    {
        public DateTime GetMealTime<T>(T meal) where T: IMealTime
        {
            return meal.Time;
        }
    }

Upvotes: 1

BFree
BFree

Reputation: 103750

You'd have to have both classes implement an interface something like this:

public interface IMyInterface
{
   DateTime Time{get;set;}
}

And then in your generic method:

public void MyMethod<T>(T item) where T: IMyInterface
{
    //here you can access item.Time
}

Upvotes: 5

Marcel Popescu
Marcel Popescu

Reputation: 3351

You can always use reflection, of course. Also, if the two types implement a common interface with a Lunch property, you can use that. (I do not understand what you mean by "Table" here.)

Upvotes: 0

Related Questions