asharpharp
asharpharp

Reputation: 169

Return object of same type as class in c#?

I have a base class with possibly many children. I have a method that needs to return the same type as the one of the class (i.e. class A returns object of type A, class B returns object of type B, etc.). Is there a good way to do it that is not declaring the same method on every class (I may need some similar methods in the future and this method could have some changes). Currently, I have a static generic method in the base class.

public static T FromJson<T>(string json) where T : IHttpModel =>
        JsonConvert.DeserializeObject<T>(json, Converter.Settings);

This is code from quicktype.io, but I may need to change it.

Upvotes: 1

Views: 454

Answers (1)

Guru Stron
Guru Stron

Reputation: 142008

If i understood your task correctly, you can declare your base class as generic and declare children (if you don't have multilevel hierarchy) passing to generic parameter the type itself:

class Base<T> where T : IHttpModel
{
    public static T FromJson(string json)=> JsonConvert.DeserializeObject<T>(json, Converter.Settings);
}

class A : Base<A>, IHttpModel
{
    
}

A x = A.FromJson("");

Upvotes: 3

Related Questions