Sunil Chaudhry Sunil Chaudhry - 26 days ago 6
C# Question

How to get abstract class constructor value in derived class

How to get abstract class constructor value in derived class.

public abstract class ABC
{
private string data = "hi";

protected ABC(string myString)
{
myString = data;
}
}
public class XYZ: ABC
{
public string abc= "";
public XYZ(string myString)
: base(myString)
{
abc = myString;
}
}

XYZ var = new XYZ("567");
Response.Write(var.abc);


I am getting 567 as output , how to get "hi567" or "567hi" or even "hi".

Answer

Pretty simple - but kinda weird:

using System;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var var = new XYZ("567");
            Console.WriteLine(var.abc);

            Console.ReadLine();
        }
    }

    public abstract class ABC
    {
        private string data = "hi";

        protected ABC(string myString, out string outString)
        {
            myString = this.data;
            outString = myString;
        }
    }

    public class XYZ : ABC
    {
        public string abc = "";

        public XYZ(string myString) : this(myString, string.Empty)
        {
        }

        private XYZ(string myString, string outString) : base(myString, out outString)
        {
            this.abc = outString + myString;
        }
    }
}

You just need to pass an out-parameter to the base constructor.