1

I don't know how to define my question (probably already asked but didn't found it).

I want to create a constructor for a class B inherited from A taking a B object as parameter used to be a copy of it.

There can be something like this :

class B : A
{
    public String NewField;

    public B(A baseItem, String value)
    {
        // Create new B to be a copy of baseItem
        ???; // something like : this = baseItem

        // Add new field
        NewField = value;
    }
}

Objective is to create an object B which is the exact copy of an A object with on filed more.

4
  • this is read-only within classes, add a copy constructor to A and call it from B's constructor. Commented Sep 13, 2017 at 12:59
  • learn.microsoft.com/en-us/dotnet/csharp/programming-guide/… Commented Sep 13, 2017 at 13:00
  • I know I can't assign this, I want to initiate the new B object to be a copy of the baseItem. Commented Sep 13, 2017 at 13:01
  • With A having a copy ctor, you'd do public B( A baseItem, string value) : base( baseItem ) { NewField = value;} Commented Sep 13, 2017 at 13:01

2 Answers 2

3

Use the base keyword to call the parent class constructor, giving your parent class instance as a parameter. Then create a copy constructor in your parent, and you're done.

class A
{
    public A(A a)
    {
        // Copy your A class elements here
    }
}

class B : A
{
    public String NewField;

    public B(A baseItem, String value)
     : base(baseItem)
    {
        NewField = value;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could implement a CopyProperties method, which will copy the properties values.

using System;

public class A
{
    public string Filename {get; set;}

    public virtual void CopyProperties(object copy)
    {
        ((A)copy).Filename = this.Filename;
    }
}

public class B : A
{
    public int Number {get;set;}

    public override void CopyProperties(object copy)
    {
        base.CopyProperties(copy);
        ((B)copy).Number = this.Number;
    }    
}


public class Program
{

    public static void Main()
    {
        B b = new B { Filename = "readme.txt", Number = 42 };

        B copy = new B();
        b.CopyProperties(copy);

        Console.WriteLine(copy.Filename);
        Console.WriteLine(copy.Number);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.