Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare Generic static method in C#

Tags:

c#

.net

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".


1 Answers

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.

like image 98
Luaan Avatar answered Aug 25 '26 11:08

Luaan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!