Question

Does auto implemented properties have the same backed field in base and derived classes in C# ? I have the following code:

class Employee
    {
        public virtual string Infos { get; set; }
    }

    class Engineer : Employee
    {
        public override string Infos
        {
            get
            {
                //Employee and Engineer share the same backed field.
                return base.Infos + " *";
            }
        }
    }

And in the Main class, i have the following code :

class Program
    {
        static void Main(string[] args)
        {
            Employee employee = new Engineer { Infos = "Name : Boulkriat Brahim" };
            Console.WriteLine ( employee.Infos );

        }
    }

Compiling and Running this code will print "Boulkriat Brahim *". So base.Info is equal to "Boulkriat Brahim".This mean that this.Info and Base.Info have the same value despite i create an object of type Engineer. Does this mean that they had the same backed field?

Was it helpful?

Solution

Yes, exactly as if you declared the properties manually. There's only one field, and all subclasses inherit it.

OTHER TIPS

In your code, there is only one backing field, because there is one auto-implemented property: Employee.Infos. Engineer.Infos is a normal property, so it doesn't have any backing field.

If you instead wrote your code like this:

class Employee
{
    public virtual string Infos { get; set; }
}

class Engineer : Employee
{
    public override string Infos { get; set; }

    public void M()
    {
        this.Infos = "Name : Boulkriat Brahim";
        Console.WriteLine(base.Infos);
    }
}

Then calling new Enginner().M() would pass null to WriteLine(), because Engineer.Infos has a different backing field than Employee.Infos.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top