virtual, const and event modifiers in C#

Goud.Kv
Posted by in C# category on for Beginner level | Points: 250 | Views : 10068 red flag

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.
Recommendation
Read abstract, sealed and override modifiers in C# before this article.

Introduction

So far, we have discussed with abstract, sealed and override modifiers (keywords) in C#. Now, let's study some other modifiers with examples in this chapter.

Objective

The main objective of this article is to learn virtual, const and event modifiers in C# programming language.

virtual

Virtual is a C# keyword which is used to modify a type and allows that type to get overridden in the derived classes. In other words, a virtual method can be overridden by any derived classes which means it is a method that can be redefined.

Syntax,
class Base
{
    protected virtual void Test() // Virtual method
    {
        ..............;
    }
}
class Derived : Base
{
    protected override void Test() // overridden method from Base class
    {
        ..............;
    }
}
Now, in the above syntax we have two classes Base and Derived (Which inherits Base). We have called the virtual methods of the Base class in the Derived class by using override keyword.

Let's have a look at the clear example below,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Base
    {
        public virtual void Test1() // virtual method with public access
        {
            Console.WriteLine("Test1 method in Base class");
        }
        protected virtual void Test2() // virtual method with protected access
        {
            Console.WriteLine("Test2 method in Base class");
        }
    }
    class Derived : Base
    {
        public override void Test1() // overridden method from the Base class
        {
            Console.WriteLine("Test1 method in Derived class");
        }
        protected override void Test2() // overridden method from the Base class
        {
            Console.WriteLine("Test2 method in Derived class");
        }
    }
    class Program
    {
        static void Main()
        {
            Base b1 = new Base(); // Both Compile time and Runtime types are same.
            b1.Test1();
            // b1.Test2(); // This gives compile time error due to its protection level

            Base b2 = new Derived(); // Runtime is Derived....
            b2.Test1();
            // b2.Test2(); // This gives compile time error due to its protection level
        }
    }
}
Note: Please read comments in the code.

In the above code, we have the Base and Derived classes with virtual and override modifiers. Based on the access level (public, private, protected etc.), methods are being called in the above code.

Now press Ctrl + F5 and see the result in your console something like,


const

const is used to declare a constant which may be a local variable or a field. It means, the types declared with const cannot be modified.
  • In C#, constants we go for can be numeric types, values, strings, null reference or boolean.
  • const keyword restricts a field to get modified at the program runtime. Any further modifications should be done in the compile time only.
  • const values are inserted into the program at the compile time
  • Look up overhead is also eliminated with const keyword.
Example code,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Program
    {
        const string Name = "Krishna"; // Declaration of constant field
        static void Main()
        {
            Console.WriteLine("Name: " + Name);
            // Name = "Vamshi";        // Modification is not allowed and gives you compile time error.s

            const int Num = 1;         // Declaration of constant local variable
            // Num = 2;                // Enabling this will gives you the compile time error
            Console.WriteLine("No: " + Num);
        }
    }
}
Note: Please read comments in the code.

If you observe the above code clearly, you will come to know that we cannot modify a const value (which gives compile time error).

The above code results the below output,


event

In order to declare any event, event modifier is used. It can have many handlers. In some cases, we need to have a notification system. This can be achieved by using event handlersWe can implement further methods easily without affecting the remaining code.

Let's have an example of creating event menu like below,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public delegate void Handler(); // Specifying the type

namespace Man
{
    class Program
    {
        public static event Handler menu;  // Declaration of event

        static void Main()
        {
            menu += new Handler(Birthdays); // Adding Birthdays to menu event
            menu += new Handler(Meetings);  // Adding Meetings to menu event
            menu += new Handler(Reminders); // Adding Reminders to menu event

            menu.Invoke();                 // Invoking the event
        }

        static void Birthdays()
        {
            Console.WriteLine("Today is Krishna's 24th birthday");
        }

        static void Meetings()
        {
            Console.WriteLine("Today's Meetings.....");
        }

        static void Reminders()
        {
            Console.WriteLine("Remind to do ......");
        }
    }
}
In the above code, we have an event 'menu' in which we are adding Birthdays, Reminders and Meetings. event stores all the methods that we have created to its event list.
We have used delegate keyword to specify the type Handler.
'+=' is used to invoke all the methods at the same time. If you remove '+' in the above code, only Reminders will be invoked.

Note: Please read comments in the code.

The above code will gives you the following output in your console,


Conclusion

In this article, we have learnt virtual, const and event modifiers (keywords) with examples. Hope you understand them.

Thanks for reading,

Regards,
Krishna.

Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)