Blendester
Blendester

Reputation: 1653

How to initialize inherited class with base class?

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?

Upvotes: 12

Views: 24579

Answers (4)

Michael Freidgeim
Michael Freidgeim

Reputation: 28511

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) ;

Upvotes: 4

Gokulan P H
Gokulan P H

Reputation: 1898

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);
                }
            });
         }

Upvotes: 13

A.T.
A.T.

Reputation: 26382

No. you can't initialize the derived instance in base class object.

However you can create seprate extension method,

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

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

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

    public static class MyClassExtension
    {
        public static MyInheritedClass ToMyInheritedClass(this MyClass obj, string email)
        {
            // You could use some mapper for identical properties. . . 
            return new MyInheritedClass()
            {
                Email = email,
                Password = obj.Password,
                Username = obj.Password
            };
        }
    }

usage:

 MyClass myClass = new MyClass { Username = "abc", Password = "123" };
 var myInheritedClass = myClass.ToMyInheritedClass("[email protected]");
 Console.WriteLine(myInheritedClass.GetJson());

output would be:

{"Email":"[email protected]","Username":"123","Password":"123"}

Upvotes: 2

Jenish Rabadiya
Jenish Rabadiya

Reputation: 6766

You just need to create an instance of child class that is MyInheritedClass and it will hold all the properties from both the classes.

When you create an instance of child class MyInheritedClass, runtime will call the constructor of Parent class MyInheritedClass first to allocate the memory for the member of parent class and then child class constructor will be invoked.

So instance of Child class will have all the properties and you are referring to the this while serializing the object so it should have all the properties serialized in json.

Note: Even though you are serializing the object inside the method that is declared in parent class, referring to this object will refer to the current instance that is instance of Child class so will hold all the properties.

Upvotes: 2

Related Questions