Pawan Nogariya
Pawan Nogariya

Reputation: 8980

Access child class object in base class overridden ToString method

I have multiple classes with all different structure. I wanted all my child classes ToString method to be overridden like this

public override string ToString()
{
    return JsonSerializer.Serialize(this);
}

So that I get a json serialized string for them.

Since I had multiple classes and I wanted exactly same thing, so I thought to have a base class where I would override the ToString method and it will work for all the sub classes, like this

public class ResponseBase
{
    public override string ToString()
    {
        return JsonSerializer.Serialize(this);
    }
}

And have child class like this

public class Response_1: ResponseBase
{
    public string Name {get;set;}
}

But when I try to do this,

Response_1 r = new Response_1();
r.Name = "Test";
var json = r.ToString(); // has empty json object "{}"

So the base class' overridden ToString method does get called because I get empty json string "{}" but it does not consider child object property while converting to json.

So basically this in this line, does not represent the child object of that time but the base object

return JsonSerializer.Serialize(this);

So the solution doesn't work.

Is there any way to achieve this? To have a ToString method overridden at one place for multiple classes?

Upvotes: 3

Views: 743

Answers (1)

DavidG
DavidG

Reputation: 119056

The issue is the that generic version of JsonSerializer.Serialize<T> method is being called, where T is ResponseBase. You can fix this two ways:

Use another overload that lets you specify the type:

return JsonSerializer.Serialize(this, this.GetType());

Cast the value to object so it calls the non-generic overload:

return JsonSerializer.Serialize((object)this);

Upvotes: 3

Related Questions