Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize inherited class with base class?

Tags:

c#

inheritance

I have an instance of this class:

public class MyClass
{
    public string Username { get; set; }
    public string Password { get; set; }

    public string GetJson()
    {
        return JsonConvert.SerializeObject(this);
    }
}

but in some cases I need more properties in serialized json. I thought I should make a second inherited class like this:

public class MyInheritedClass : MyClass
{
    public string Email { get; set; }
}

If I'm not solving the problem in the wrong way, how can I initialize a new instance of my second class with an instance of the first one and have a json string from GetJson() that contains all the three properties?

like image 854
Blendester Avatar asked Jun 22 '17 06:06

Blendester


People also ask

Can you instantiate a base class?

Abstract base classes cannot be instantiated. Instead, they are inherited and extended by the concrete subclasses. Subclasses derived from a specific abstract base class must implement the methods and properties provided in that abstract base class.

Can be inherited by a derived class from a base class?

The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive.

How do you initialize a parent class in Python?

When you initialize a child class in Python, you can call the super(). __init__() method. This initializes the parent class object into the child class. In addition to this, you can add child-specific information to the child object as well.


2 Answers

You can create a constructor in your derived class and map the objects,

public class MyInheritedClass : MyClass
{
    MyInheritedClass (MyClass baseObject)
    {
        this.UserName = baseObject.UserName; // Do it similarly for rest of the properties
    }
    public string Email { get; set; }
}

MyInheritedClass inheritedClassObject = new MyInheritedClass(myClassObject);
inheritedClassObject.GetJson();

Updated Constructor :

        MyInheritedClass (MyClass baseObject)
         {      
           //Get the list of properties available in base class
            var properties = baseObject.GetProperties();

            properties.ToList().ForEach(property =>
            {
              //Check whether that property is present in derived class
                var isPresent = this.GetType().GetProperty(property);
                if (isPresent != null && property.CanWrite)
                {
                    //If present get the value and map it
                    var value = baseObject.GetType().GetProperty(property).GetValue(baseObject, null);
                    this.GetType().GetProperty(property).SetValue(this, value, null);
                }
            });
         }
like image 93
Gokulan P H Avatar answered Oct 17 '22 00:10

Gokulan P H


One of the options is to serialize the base class object and then deserialize it to derived class.
E.g. you can use Json.Net serializer

 var jsonSerializerSettings = new JsonSerializerSettings
            {  //You can specify other settings or no settings at all
                PreserveReferencesHandling = PreserveReferencesHandling.Objects,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore 
            };
 string jsonFromBase = JsonConvert.SerializeObject(baseObject, Formatting.Indented, jsonSerializerSettings);
 derivedClass= JsonConvert.DeserializeObject<DerivedClass>(jsonFromBase) ;
like image 38
Michael Freidgeim Avatar answered Oct 17 '22 01:10

Michael Freidgeim