.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> Design Patterns >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Use of new,Virtual,Override key words with small example program

Posted By:Krishna       Posted Date: April 12, 2012    Points: 25    Category: Design Patterns    URL: http://www.dotnetspark.com  

Here I want to explain basic C# keywords with sample examples.
 

class Base

    {

        public void show()

        {

            Console.WriteLine("Base class Show method");

        }

        public void Show1()

        {

            Console.WriteLine("Base class Show1 method");

        }

        public  virtual void Show2()

        {

            Console.WriteLine("Base class Show2 method");

        }



    }

    class derived : Base

    {

        public void show()

        {

            Console.WriteLine("derived class Show method");

        }

        public new void Show1()

        {

            Console.WriteLine("derived class Show1 method");

        }

        public override void Show2()

        {

            Console.WriteLine("derived class Show2 method");

        }



    }

    class Example2

    {

        static void Main(string[] args)

        {

            Base _obj = new Base();

            _obj.show();

            _obj.Show1();

            _obj.Show2();

            Console.Read();



            Base _obj1 = new derived();

            _obj1.show();

            _obj1.Show1();//Don't expect that this will get call derived class method this "the new key word just hide the method.

            _obj1.Show2();//in case of this method we had overriden so this method will get call from derived method of show2();

            Console.Read();



            derived _obj2 = new derived();

            _obj2.show();

            _obj2.Show1();

            _obj2.Show2();

            Console.Read();



            

        }

    }

Output:

Base class show method 
 Base class show1 method 
 Base class show2 method 

 Base class show method 
 Base class show1 method 
 derived class show2 method 

 derived class show method 
 derived class show1 method 
 derived class show2 method

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend