Noel Widmer
Noel Widmer

Reputation: 4572

C# Linq DataContext Table: A polymorph cast

I am trying to write a method:

public Table<ParentType> GetTableFromContext()    {
   //return a table of type Table<ChildType> 
}

Yes, I could solve this using Generics:

public Table<T> GetTableFromContext<T>() where T : ParentType   {
   //return a table of type Table<T> 
}

But I'd prefer not to. (I'd have to use generics in all base classes then)
Is there a solution to refer to a table with a less specific type?

Upvotes: 1

Views: 90

Answers (2)

Slava Utesinov
Slava Utesinov

Reputation: 13498

You can solve this problem with the help of covariation, but at this case you should use interface ITable instead of class Table as return type of your method:

public interface ITable<out T>
{}

public class Table<T> : ITable<T>
{}    

public ITable<ParentType> GetTableFromContext() {
    return new Table<ChildType>();
}

Upvotes: 1

r_c
r_c

Reputation: 176

As far as I understand, your problem is "I want to return one of a few types, but I don't want a complicated inheritance". If this is so, your solution is a marker interface

public interface ITable {}

Which can be implemented (with no interface members it's very simple) by your return types

public class ChildType1 : ITable

Additionally, the interface can serve to enforce a common structure on your entities, if they have any (the most common example is probably an Id property)

Upvotes: 1

Related Questions