Is it wrong to initialize a virtual property in the constructor? It just does not feel right because if you override the property in a derived class the property will first be initialized with the value from the base class constructor then it will be assigned again by the derived class constructor. is there an alternative for doing this? I'm talking about something like this
internal class B1
{
public B1()
{
Ti = "Hello";
}
public virtual string Ti { get; set; }
}
internal class B2 : B1
{
public B2()
{
Ti = "HelloKitty";
}
public override string Ti { get; set; } //<--"Hello" will be assigned first then "HelloKitty" will be assigned
}
internal class Program
{
private static void Main(string[] args)
{
var b2 = new B2();
Console.WriteLine(b2.Ti);
Process.GetCurrentProcess().WaitForExit();
}
}
UPDATE 1: As recommended by @AK_
internal class Bb1
{
private string _ti;
public Bb1()
{
_ti = "Hello";
}
public virtual string Ti
{
get { return _ti; }
set { _ti = value; }
}
}
internal sealed class Bb2 : Bb1
{
public Bb2()
{
Ti = "HelloKitty";
}
public override string Ti { get; set; }
}
the variable _ti in the base class is initialized by "Hello".
what if instead of string type I'm using type which explicitly needs to be exposed?