Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I need to use a virtual modifier in a c# class?

Tags:

c#

I have the following class:

public class Delivery
{
// Primary key, and one-to-many relation with Customer
   public int DeliveryID { get; set; }
   public virtual int CustomerID { get; set; }
   public virtual Customer Customer { get; set; }

// Properties
   string Description { get; set; }
}

Can someone explain why they Customer information is coded with virtual. What does it mean?

like image 779
Samantha J T Star Avatar asked Mar 17 '12 13:03

Samantha J T Star


3 Answers

Judging by the comments, you are learning Entity Framework?

virtual here would mean you are trying to use lazy loading - when related items like Customer can be loaded by EF automatically

http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx

For example, when using the Princess entity class defined below, the related unicorns will be loaded the first time the Unicorns navigation property is accessed:

public class Princess 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<Unicorn> Unicorns { get; set; } 
}
like image 160
AFD Avatar answered Oct 17 '22 10:10

AFD


Can someone explain why they Customer information is coded with virtual. What does it mean?

The virtual keyword means that a super class derived from this base class (i.e. Delivery) can override that method.

If the method was not marked as virtual then it would not be possible to override that method.

like image 4
high5 Avatar answered Oct 17 '22 11:10

high5


Guess you are using EF.

What happens when you make a NavigationProperty virtual is that EF dynamically creates a derived class.
That class implements functionality that allows for lazy loading and other tasks like maintaining relations that EF performs for you.

Just to get the idea your sample class dynamically becomes something like this:

public class DynamicEFDelivery : Delivery 
{
   public override Customer Customer 
   { 
     get
     {
       return // go to the DB and actually get the customer
     } 
     set
     {
       // attach the given customer to the current entity within the current context
       // afterwards set the Property value
     }
   }
}

You can easily see this while debugging, the actual instance types of your EF classes have very weird names, since they are generated on the fly.

like image 1
ntziolis Avatar answered Oct 17 '22 09:10

ntziolis