24

I am working through a tutorial 'Professional ASP.NET MVC 3' by J Galloway. In this tutorial, Jon shows us how to build the MVC music store.

I am at the part where we are creating CS classes to model the data using EF code first.

I all the examples in the book, public virtual int property {get; set; } is used with no explanation. The term virtual is stuffed EVERYWHERE.

Elsewhere on the web, I have not seen the term virtual used with any kind of concistency whatsoever.

Could anybody explain to me:

  1. The purpose of the term 'virtual' in this particular context
  2. Is using 'virtual' necessary?
  3. Why do some people use 'virtual' and others do not?
  4. Why do some people only use 'virtual' when defining foreign keys?
  5. What is the best practice use of the term 'virtual'?

Many thanks in advance

Mark Oreta
  • 10,346
  • 1
  • 33
  • 36
Gravy
  • 12,264
  • 26
  • 124
  • 193
  • possible duplicate of [Virtual functions](http://stackoverflow.com/questions/6520394/virtual-functions) and http://stackoverflow.com/questions/1062102/practical-usage-of-virtual-functions-in-c-sharp – dash Oct 01 '12 at 18:30
  • Wasn't aware that virtual functions and virtual properties were one and the same thing??? – Gravy Oct 01 '12 at 18:34
  • 1
    It's the `virtual` keyword that's important :-) Regardless of whether it's a function or a property, if it's not marked as virtual, then unless a descendant uses the `new` keyword, they have to take the implementation as defined in the base class. Imagine you had a class called person, with a property called "Name". If you didn't mark it as a virtual property, all descendants of Person would, by default, get that property as their name. If you make it virtual (or use the new keyword) you can override (or, in the case of new, replace) that implementation with a more specific one. – dash Oct 01 '12 at 18:35
  • 1
    I dont know the book, but check if the virtual keyword is not used for mocking purposes on Unit Testing. – gustavodidomenico Oct 01 '12 at 18:36

7 Answers7

12

In order to truly understand the virtual keyword you are going to want to read up on Polymorphism in general:

Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and inheritance. Polymorphism is a Greek word that means "many-shaped" and it has two distinct aspects:

  1. At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object's declared type is no longer identical to its run-time type.

  2. Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.

Once you understand these concepts better you might be able to determine whether or not the method you are creating from the book needs to be virtual or not.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
7

Could anybody explain to me:

  1. The purpose of the term 'virtual' in this particular context

    Other users here answered this well with very good references.

  2. Is using 'virtual' necessary?

    It depends. Sometimes it is necessary, sometimes it is superfluous.

  3. Why do some people use 'virtual' and others do not?

    They use it when they need it, or when they think they might need it.

  4. Why do some people only use 'virtual' when defining foreign keys?

    When defining foreign keys for use by Object Relational Mapping tools like Entity Framework and NHibernate, virtual is often necessary because these ORM tools dynamically create a new class that inherits from your class. These "dynamic proxy" classes override your virtual properties to provide additional behavior needed to maintain foreign key consistency. In the case of NHibernate, all properties (not just foreign keys) must be marked virtual. This is because NH dynamic proxies add custom behavior to decide which properties on your model to retrieve from the database, and which to avoid loading.

  5. What is the best practice use of the term 'virtual'?

    Use it when you intend for a member (method or property) to be overridden in a more derived class. Do not use them in classes marked sealed.

danludwig
  • 46,965
  • 25
  • 159
  • 237
4

Ok, so the term virtual, is basically meaning "overridable" (has base implementation), but not abstract (meaning no original implementation).

The 'virutal' keyword is nessisary if you WANT someone to override your method or property, instead of 'hide' it.

So this all applies to inheritance and polymorphism. A derived class can override a virtual method and make it's own implementation (or even call the base implementation in that method). By overriding, you can guarentee that your new method will be called polymorphically, instead of the base implementation.

Inversly, using the 'new' keyword, you can 'hide' data members and methods. This will allow you to do your own implementation as well, but DOES NOT execute your new implementation polymorphically, it will use the base class implementation.

Virual Keyword

Versioning with the Override and New Keywords (C# Programming Guide)

iMortalitySX
  • 1,478
  • 1
  • 9
  • 23
4

The reason that he uses the virtual keyword in his model is to enable Change Tracking proxies. This is something specific to Entity Framework (edit: also NHibernate, and possibly any other orm thanks @danludwig), and it allows EF to automatically manage the entities that you're mapping to the database.

From MSDN:

Each property that is mapped to a property of an entity type in the data model must have non-sealed (NotOverridable in Visual Basic), public, and virtual (Overridable in Visual Basic) get and set accessors.

Mark Oreta
  • 10,346
  • 1
  • 33
  • 36
  • You also need to mark properties as `virtual` in NHibernate, so technically it's not specific to EF. NHibernate also uses dynamic proxies for FK management and property eager/lazy loading purposes. – danludwig Oct 01 '12 at 22:17
1

See virtual (C# Reference) . Adding the virtual keyword allows the property to be overriden in derived classes, which is very likely when you're building the generalized base classes of an MVC app.

Community
  • 1
  • 1
Joshua Honig
  • 12,925
  • 8
  • 53
  • 75
0

From docs

The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class.

So if you need hide old functionality and add new one you can use virtual. The different applications need difference requrementce according on develop new modules and architecture..

see here http://msdn.microsoft.com/en-us/library/9fkccyh4(v=vs.80).aspx

Anton Baksheiev
  • 2,211
  • 2
  • 14
  • 15
0

Virtual ensures that inherited children classes override the base class by enforcing them to override the property. Without it the virtual keyword, a children object can't override the base functionality.

Christopher Bales
  • 1,069
  • 1
  • 13
  • 23