3

I am pretty new to C#. I have two classes a Movie class and a Genre class.I cant understand the property "public virtual Genre Genre" Could someone explain me this? Following are the two classes

 public class Genre :IEntityBase
{
    public Genre()
    {
        Movies = new List<Movie>();
    }
    public int ID { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<Movie> Movies { get; set; }
}


public class Movie:IEntityBase
{
     public Movie() 
     {                                                          
         Stocks = new List<Stock>(); 
     }
     public int ID { get; set; }          
     **public virtual Genre Genre { get; set; }** 
     public virtual ICollection<Stock> Stocks { get; set; }
}
hEShaN
  • 551
  • 1
  • 9
  • 27
  • Also, see this question (your classes look like EF model): http://stackoverflow.com/questions/8542864/why-use-virtual-for-class-properties-in-entity-framework-model-definitions – Dennis Feb 20 '16 at 11:43

2 Answers2

6

public virtual Genre Genre { get; set; } means the following:

  1. Declare a property named Genre (the second occurrence)
  2. This property is of type Genre (the first occurrence)
  3. This property can be read (get) and can be changed (set).
  4. This property can be read or set by any other class in any other library that has access to this object (public)
  5. This property can be overridden (have it's code replaced to do something different) by a subclass. (virtual).
yaakov
  • 5,552
  • 35
  • 48
1

The type and the name are Gender which to you might look confusing but for the computer it's like this:

a bunch of modifiers like public, private etc. + the type + the name

So it actually doesn't consider the second Gender as a type because it's just a name for something. Under the hood, it's not referring to the variable/properties you create by their name anyway. It uses some kind of pointer or reference.

Now, if you mean to ask how to interpret that particular definition, it says that the property is supposed to be seen outside the class (it's not hidden/private). It's also possible to alter its meaning if you use inheritance. It will return something of type Gender (the class) and it's name is Gender (and it could be called almost anything, if you wish). I t also says that it will work as a container for that Gender-like value and you can freely assign it and read it.

Most of the details are of importance and can be seen to modify the behavior when you start using the instances of it in a bigger scope. Just in this example, it's really no difference if you go public or virtual. Did it help?

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438