1

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.

3
  • This question is rather confusing. A code sample or some pseudo-code would help. Commented Jun 1, 2009 at 20:25
  • Added some pseudocode, and got a good answer meanwhile :) Commented Jun 1, 2009 at 20:38
  • Remember, generics are not templates. Everything you do with the type parameter has to be resolvable based solely on the constraints on the type parameter. Commented Jun 1, 2009 at 22:40

3 Answers 3

5

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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;
        }
    }

1 Comment

Great explanation. Came after the first answer in the same direction, but anyways thank you. :)
0

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.