Search code examples
c#.netgenericsclass-extensions

Is there a way to make an extension for a generic type object?


so I'm trying to make an exception to map my C# class to an proto object via extension methods it doesn't seem to accept a generic type for "this"?

 public static ResponseReply ToProtoObject(this Response<T> reply) {
        ResponseReply answer = new() { 
            Succes = reply.Success
        };
        if (reply.Object != null)
        {
            answer.ObjectId = reply.Object.Id.ToString();
        }

        if (reply.Messages != null)
        {
            answer.Messages.AddRange(reply.Messages.Select(x => x.ToProtoObject()));
        }


        return answer;
    }

these are the base classes from the Response

    public class Response<T> where T : BaseObjectBo
{
    public T Object { get; set; }
    public bool Success { get; set; }
    public List<Message> Messages { get; set; }
}
public class BaseObjectBo
{
    public Guid Id { get; set; }
}

Solution

  • Note, you just need to add <T> to your method signature.

    public static ResponseReply ToProtoObject<T>(this Response<T> reply) 
        where T : BaseObjectBo