Sadegh
Sadegh

Reputation: 4341

How to cast a generic class to a generic interface in C#

according to below definitions

interface myin
{
    int id { get; set; }
}
class myclass:myin
{
    public int id { get; set; }
}
[Database]
public sealed class SqlDataContext : DataContext, IDataContext
{
    public SqlDataContext(string connectionString) : base(connectionString){}
    public ITable<IUrl> Urls
    {
        get { return base.GetTable<Url>(); }  //how to cast Table<Url> to ITable<IUrl>?
    }
    ...
}

Update:

public IEnumerable<IUrl> Urls
{
    get { return base.GetTable<Url>(); }
}

so by use above approach, i haven't Table class associated methods and abilities. this is good solution or not? and why?

Upvotes: 2

Views: 295

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243041

In C# 3.0 and odler this is not easily possible - see also covariance and contravariance in C# 4.0.

The problem is that Table<Url> implements the ITable<Url> interface - this part of the casting is easy. The tricky bit is casting ITable<Url> to ITable<IUrl>, because these two types aren't actually related in any way...

In C# before 4.0, there is no easy way to do this - you'll explicitly need to create a new implementation of ITable<..> for the right generic type (e.g. by delegation). In C# 4.0, this conversion can be done as long as ITable is a covariant interface.

Upvotes: 4

Related Questions