virtual properties

In Entity Framework (which I believe your example refers to), your POCO classes are created and wrapped into a proxy class. Proxy class is a descendant of the class that you declare, so your class A becomes a base class. This proxy class is populated with data and returned back to you. This is necessary in order to track changes. Have a look at this article http://technet.microsoft.com/en-us/query/dd456848

I had a similar problem in trying to understand this and after a few debugging sessions and seeing the proxy classes and reading about tracking changes it made be figure out why it is declared the way it is.


In object-oriented programming, a virtual property is a property whose behavior can be overridden within an inheriting class. This concept is an important part of the polymorphism portion of object-oriented programming (OOP).

look at the example below:

public class BaseClass
{

    public int Id { get; set; }
    public virtual string Name { get; set; }

}

public class DerivedClass : BaseClass
{
    public override string Name
    {
        get
        {
            return base.Name;
        }

        set
        {
            base.Name = "test";
        }
    }
}

at the presentation level:

        DerivedClass instance = new DerivedClass() { Id = 2, Name = "behnoud" };

        Console.WriteLine(instance.Name);

        Console.ReadKey();

the output will be "test", and not "behnoud", because the "Name" property has been overridden in the derived class(sub class).


public virtual ICollection<B> Prop { get; set; }

Translates almost directly to:

private ICollection<B> m_Prop;

public virtual ICollection<B> get_Prop()
{
    return m_Prop;
}

public virtual void set_Prop(ICollection<B> value)
{
    m_Prop = value;
}

Thus, the virtual keyword allows you to override the property in sub-classes just as you would the above get/set methods:

public override ICollection<B> Prop
{
    get { return null; }
    set { }
}

Tags:

C#