Setting base class property using derived class Constructor
c#
Solution
Pass the field down in the constructor. (Note: normally you should name fields starting with a lower case character and properties with uppercase). Here is an example where I fixed the naming.
public abstract class Converter
{
private readonly MyData data;
protected Converter(MyData data)
{
this.data = data;
}
public MyData Data { get { return data; } }
}
public class MyData
{
private readonly int value;
public MyData(int value)
{
this.value = value;
}
public int MyValue { get { return value; } }
}
public class Converter1 : Converter
{
public Converter1()
: base(new MyData(5))
{
}
}
I recommend the practice of using readonly fields and getters only for properties to start with. Doing so will make your types immutable which usually helps get your program correct initially. Start off immutable and then introduce mutability where you need it, and only once you need it. Having the types immutable like this requires passing the values through the constructor.
Problem
I am setting a property of base class from derived class as following: ``` public abstract class Coverter { public Mydata data { get; set; } public abstract void Convert(); } public class Mydata { public int i; } public class Coverter1 : Coverter { public Coverter1(Mydata data1) { data = data1; } public override void Convert() { Console.WriteLine(data.i.ToString()); } } private static void Main(string[] args) { Mydata data = new Mydata(); data.i = 5; Coverter c = new Coverter1(data); c.Convert(); Console.ReadLine(); } ``` Is there any flaw with this kind of implementation ? What could be the better approach? I can do the same thing in the following approach. ``` public abstract class Coverter { public Mydata data { get; set; } public abstract void Convert(); } public class Mydata { public int i; } public class Coverter1:Coverter { override public void Convert() { Console.WriteLine(data.i.ToString()); } } static void Main(string[] args) { Mydata data1 = new Mydata(); data1.i = 5; Coverter c = new Coverter1(); c.data = data1; c.Convert(); Console.ReadLine(); } ``` Which appraoch is better?