0

I would like to avoid writing the same line of code in all my derived classes. I have the following structure:

using Newtonsoft.Json;

public class BaseClass
{
    public string BaseProperty { get; set; }
    public string Serialize() { return JsonConvert.SerializeObject(this); }
}

public class DerivedClass : BaseClass
{
    public string DerivedProperty { get; set; }
}

What happens when Serialize() is called from DerivedClass? Is this smart enough to know that the child object contains an extra property? Or, am I limited to writing this same line of code in each child of BaseClass?

1 Answers1

1

Some language features / behaviors are easy to experiment with... Considering the following code:

public class A
{
    public string WhoAmI => this.ToString();
}

public class B:A { }

Your question is equivalent to asking what Console.WriteLine(new B().WhoAmI) prints out?

Well, if in doubt, run it and see... it takes less than 1 minute.

this is a reference to an object, and behaves as any other reference, it simply has a special name.

Considere the following:

A a = new B();

Now you have a B instance referenced by an A typed reference a, but the instance is still a B. In your case this inside BaseClass is simply a BaseClass reference to whatever instance has been created. Do not confuse the type of a reference pointing to an object with the type of the object itself, they need not be the same.

InBetween
  • 32,319
  • 3
  • 50
  • 90