user4868481
user4868481

Reputation:

Declare Generic static method in C#

Is there any way to declare a generic static method in C#?
For example:

public static class Class<T,P> 
    where T:class
    where P:class
{

    public static T FromTtoP (this P ob)
    {
    ...
    }

}

this code does not work . I want to map from DTO to DAL and and vice-versa.

I have tried making the class non-generic

public static class Class
{

    public static TDTO MapToDTO<TDTO, TDAL>(this TDAL dal)
                where TDTO : class
                where TDAL : class
            {

            }
}

I get an error message from "this".

Upvotes: 5

Views: 33216

Answers (2)

Carlo Saccone
Carlo Saccone

Reputation: 116

@luaan I disagree on the "kind of useless" part. We used it to create a generic mapper in a base controller class, and it's super helpful:

    public static DTOClass MightyMap<DTOClass, SourceClass>(SourceClass obj)
        where DTOClass : class
        where SourceClass : class
    {
        var dto = (DTOClass)Activator.CreateInstance(typeof(DTOClass));
        dto.InjectFrom(obj); //Using Omu.ValueInjecter
        return dto;
    }

Used like this:

IQueryable<MyEntity> query = somequery;    
var mappedItems = (await query.Select(f=> MightyMap<MyDTO, MyEntity>(f)).ToListAsync());

Upvotes: 2

Luaan
Luaan

Reputation: 63732

You can't have an extension method in a generic class. Instead, make the method generic, and keep the class non-generic.

For example:

public static class MyExtensions
{
  public static T ConvertToT<T, P>(this P ob)
    where T : class
    where P : class
  {
    // ...
  }
}

Of course, this will not really work well - there's no way to infer the arguments for the method call, which makes this kind of useless.

Upvotes: 28

Related Questions