Sam P
Sam P

Reputation: 127

How to define extension methods for generic class?

I am having a generic interface as:

public IRepository< T >
{

    void Add(T entity);

}

and a class as:

public class Repository< T >:IRepository< T >
{

    void Add(T entity)
    {      //Some Implementation
    }

}

Now I want to make an extension method of the above interface. I made the following class:

public static class RepositoryExtension

{

    public static void Add(this IRepository< T > dataAccessRepository, T entity, string additionalValue)

    {
        //Some Implementation
    }

}

But I get error in the extension Add method. It doesn't recognize the Type 'T' I have passed to IRepository. I cannot event pass this Type to my Extenstion Methods class i.e RepositoryExtension< T >. Please guide the appropriate way.

Upvotes: 8

Views: 3014

Answers (2)

Ramesh
Ramesh

Reputation: 11

IRepository<Employee> employeeRepository = new Repository<Employee>(); 
employeeRepository.Add(entity);

But in the case you suggested I'd be passing the type to The extension method too as:

employeeRepository<Employee>(entity,"someValue")

http://just-dotnet.blogspot.in/2012/06/c-generics-introduction.html

Upvotes: 1

Rohith
Rohith

Reputation: 2071

public static void Add<T>(this IRepository< T > dataAccessRepository, T entity, string additionalValue)

Try that. Notice the <T> immediately after the Add

Upvotes: 17

Related Questions