Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "protected" and "virtual/override"

Tags:

c#

oop

I couldn't understand the need or purpose of "protected" when i have "virtual/override" could someone explain me what do i need those 2 things if they are almost the same.

Edit:

Thanks for all the helpers, i now understand that "protected" is only for visibility purposes, while virtual/override is for class behavior.

like image 683
Orel Eraki Avatar asked Oct 30 '12 18:10

Orel Eraki


People also ask

What is the difference between override and virtual?

The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be overridden in the derived class. The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or event of base class into a derived class.

Should I use Virtual with override?

So the general advice is, Use virtual for the base class function declaration. This is technically necessary. Use override (only) for a derived class' override.

What is protected override?

If the superclass method is protected, the subclass overridden method can have protected or public (but not default or private) which means the subclass overridden method can not have a weaker access specifier.

What is virtual overriding?

The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class. For example, this method can be overridden by any class that inherits it: Use the new modifier to explicitly hide a member inherited from a base class.


1 Answers

  • protected means private for current class and derived classes
  • virtual means it can be used as-is but also be overridden in derived classes

Maybe it is better with some code instead of things you have probably already read, here is a little sample you can play with. Try removing the comments (//) and you can see that the compiler tells you that the properties cannot be accessed

[TestFixture]
public class NewTest
{
    [Test]
    public void WhatGetsPrinted()
    {
        A a= new B();
        a.Print();  //This uses B's Print method since it overrides A's
        // a.ProtectedProperty is not accesible here
    }
}

public class A
{
    protected string ProtectedProperty { get; set; }

    private string PrivateProperty { get; set; }

    public virtual void Print()
    {
        Console.WriteLine("A");
    }
}

public class B : A
{
    public override void  Print() // Since Print is marked virtual in the base class we can override it here
    {
        //base.PrivateProperty can not be accessed hhere since it is private
        base.ProtectedProperty = "ProtectedProperty can be accessed here since it is protected and B:A";
        Console.WriteLine("B");
    }
}
like image 187
Johan Larsson Avatar answered Sep 22 '22 02:09

Johan Larsson