ChampChris
ChampChris

Reputation: 1631

C# Class Typing with parameters

I have c# class that take type parameters

 public abstract class Repository<TDomainType, TIdType, TDatabaseType>
    : IUnitOfWorkRepository
    where TDomainType
    : IAggregateRoot
    where TDatabaseType : class

this base class i want actually us in normal and security sections of my applications, and for the sake of not repeating code I would like to do something like this:

 public class PmRepository<TDomainType, TIdType, TDatabaseType> : Repository<TDomainType, TIdType, TDatabaseType>

Is there a way to accomplish this?

EDIT Sorry didnt the error I am getting as I thought there was problem doing this.

The error I am getting is this

The type 'TDatabaseType' must be a reference type in order to use it as parameter 'TDatabaseType' in the generic type or method 'Repository<TDomainType, TIdType, TDatabaseType>'   

and

The type 'TDomainType' cannot be used as type parameter 'TDomainType' in the generic type or method 'Repository<TDomainType, TIdType, TDatabaseType>'. There is no boxing conversion or type parameter conversion from 'TDomainType' to 'ThunderCat.Core.Domain.IAggregateRoot'.    

Upvotes: 1

Views: 112

Answers (3)

eric
eric

Reputation: 1

There is another example in Microsoft's official website for C#.

See here: [https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/types][1]

public class PointFactory(int numberOfPoints)
{
    public IEnumerable<Point> CreatePoints()
    {
        var generator = new Random();
        for (int i = 0; i < numberOfPoints; i++)
        {
            yield return new Point(generator.Next(), generator.Next());
        }
    }
}

Upvotes: -1

kdbanman
kdbanman

Reputation: 10557

Your inheriting class needs the same constraints as the superclass:

public class PmRepository<TDomainType, TIdType, TDatabaseType>
    : Repository<TDomainType, TIdType, TDatabaseType>
    where TDomainType : IAggregateRoot
    where TDatabaseType : class

Upvotes: 2

Amir Popovich
Amir Popovich

Reputation: 29836

Simply add the constraints to the new class as well:

where TDomainType : IAggregateRoot
where TDatabaseType : class

public class PmRepository<TDomainType, TIdType, TDatabaseType> : Repository<TDomainType, TIdType, TDatabaseType>
    where TDomainType : IAggregateRoot
    where TDatabaseType : class

If the new class will not have those constraints then you could access the base class using the inherited class without the restrictions.

Upvotes: 1

Related Questions