You must Sign In to post a response.
  • Category: ASP.Net MVC

    Use of Virtual keyword in methods

    Friends,

    Please explain the use of below code.
    Type 1:
    Public virtual async Task<ActionResult> methodname()
    {}

    Type 2:
    public virtual ActionResult methodname()
    {}

    why do we use public virtual what is the use?
  • #769613
    By default, methods are non-virtual. We can't override a non-virtual method.
    We can't use the virtual modifier with the static, abstract, private or override modifiers.

    Name : Dotnet Developer-2015
    Email Id : kumaraspcode2009@gmail.com

    'Not by might nor by power, but by my Spirit,' says the LORD Almighty.

  • #769655
    Generally ,we can't change or modify method, event, property or relevant event without virtual keyword in C#. if you want to modify the above said items then we have to mark the method with virtual

    let us say i have a class where i can have 2 methods
    class DML
    {
    public virtual void Edit() { }
    public virtual void Delete() { }
    public virtual void Reactive() { }
    }

    So, now i want to edit or override the above method in my derived class then

    class DML1 : DML
    {
    public override void Reactive() { }
    }

    The override keyword ensure that any objects derived from DML1 will use the derived class version of Reactive(). Objects derived from DML1 can still access the base class version of Reactive() by using the base keyword.

    Hope you understood the purpose of virtual keyword in C#.

    Thanks!
    B.Ramana Reddy


  • Sign In to post your comments