I need help understanding how C# uses Virtual and also how ICollection is used when Virtual is applied [closed]

StackOverflow https://stackoverflow.com/questions/22596298

  •  19-06-2023
  •  | 
  •  

Question

I researched the Key Word Virtual and found that it allows an object's method to be overwritten. I also looked at ICollection and learned of the two options to implement it. So, if I saw someone create an Object say:

public class Lecture:

and I had the two methods for it:

public virtual ICollection<Attendance> AttendanceList { get; set; }
public virtual Room Room { get; set; }

What could these two methods be telling me?

Was it helpful?

Solution

"The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. For example, this method can be overridden by any class that inherits it" (MSDN). It allows the next class that will be inheriting from it to override this method. The code below is directly from that MSDN article.

public class Shape
{
    public const double PI = Math.PI;
    protected double x, y;
    public Shape()
    {
    }
    public Shape(double x, double y)
    {
        this.x = x;
        this.y = y;
    }

    public virtual double Area()
    {
        return x * y;
    }
}

public class Circle : Shape
{
    public Circle(double r) : base(r, 0)
    {
    }

    public override double Area()
    {
        return PI * x * x;
    }
}

Here's a simple program that should give you the idea of what "virtual" does. You should now be able to answer your own question :)

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