virtual vs override vs new keywords in c#

7
Ask a Question READER LEVEL: ARTICLE This article explains the basic differences between the three most frequently used and confusing keywords in C#. Virtual vs Override vs New Keywords in C# By Abhishek Jaiswal on Sep 08, 2014 The purpose of writing this article is simple; to provide a simple and fresh demonstration of the basic differences between these three frequently used and confusing keywords in C# with some reference example. This article is purely for the beginner in C#. Outlines Overview Introduction Virtual Keyword Override Keyword New Keyword Demo Examples Sample Implementation New Keyword Virtual and Override Keyword Method Overloading + Riding Key Points Conclusions Overview In this article I'll explain how virtual, override and new keywords vary by taking some set of examples respectively ﴾some sort of functionality﴿. Finally there will be some key points to remember about all these 3 keywords. Introduction This introductory part will provide a brief introduction of all these 3 keywords. So here they are. Virtual Keyword The Virtual keyword is used for generating a virtual path for its derived classes on implementing method overriding. The Virtual keyword is used within a set with an override keyword. It is used as: 01. // Base Class 02. class A 03. { 04. public virtual void show() 05. { 06. Console.WriteLine( "Hello: Base Class!" ); 07. Console.ReadLine(); 08. } 09. } Override Keyword The Override keyword is used in the derived class of the base class in order to override the base class method. The Override keyword is used with the virtual keyword, as in: 01. // Base Class 02. class A 03. { 04. public virtual void show() 05. { 06. Console.WriteLine( "Hello: Base Class!" ); 07. Console.ReadLine(); 08. } 09. } 10. 11. // Derived Class 12. class B:A 13. { 14. public override void show() 15. { 16. Console.WriteLine( "Hello: Derived Class!" ); 01 Lotus Notes to SharePoint Migration Using QUEST 02 Google+ Authentication in ASP.Net 03 Basics of AngularJS: Part 1 04 Angular JS Filter, Sorting and Animation Using MVC and WCF Rest 05 How to Retrieve All Users From the Group in SharePoint Using REST API 06 Creating Dynamic DataGridView Using Helper Class 07 Terminologies in MVC: Part 1 (ViewData, ViewBag, TempData) 08 MVC AngularJS and WCF Rest Service For Mind Reader Quiz 09 Angular JS Shopping Cart Using MVC and WCF Rest Service 10 Basic Terminology of SQL Server View All TRENDING UP Follow @csharpcorner 14.6K followers In Focus MUST READ: Authors How to improve your Writing Skills Contribute Lotus Notes to SharePoint Migration ... C# Corner Search 10946 5 3 Find us on Facebook C# Corner 87,746 people like C# Corner. Like TECHNOLOGIES ANSWERS BLOGS VIDEOS INTERVIEWS BOOKS NEWS CHAPTERS CAREER ADVICE JOBS

Upload: srihari

Post on 14-Nov-2015

24 views

Category:

Documents


4 download

DESCRIPTION

Diffrence between Virtual vs Override vs New Keywords in C#

TRANSCRIPT

  • 13/04/2015 VirtualvsOverridevsNewKeywordsinC#

    http://www.csharpcorner.com/UploadFile/2072a9/virtualvsoverridevsnewkeywordsincsharp/ 1/7

    Ask a Question

    READER LEVEL:ARTICLE

    This article explains the basic differences between the three most frequently used andconfusing keywords in C#.

    Virtual vs Override vs New Keywords in C#By Abhishek Jaiswal on Sep 08, 2014

    The purpose of writing this article is simple; to provide a simple and fresh demonstration of the basicdifferences between these three frequently used and confusing keywords in C# with some referenceexample. This article is purely for the beginner in C#.

    Outlines

    OverviewIntroduction

    Virtual KeywordOverride KeywordNew Keyword

    Demo ExamplesSample ImplementationNew KeywordVirtual and Override KeywordMethod Overloading + Riding

    Key PointsConclusions

    Overview

    In this article I'll explain how virtual, override and new keywords vary by taking some set of examplesrespectively some sort of functionality.Finally there will be some key points to remember about all these 3 keywords.

    Introduction

    This introductory part will provide a brief introduction of all these 3 keywords. So here they are.

    Virtual Keyword

    The Virtual keyword is used for generating a virtual path for its derived classes on implementingmethod overriding. The Virtual keyword is used within a set with an override keyword. It is used as:

    01. //BaseClass02. classA03. {04. publicvirtualvoidshow()05. {06. Console.WriteLine("Hello:BaseClass!");07. Console.ReadLine();08. }09. }

    Override Keyword

    The Override keyword is used in the derived class of the base class in order to override the base classmethod. The Override keyword is used with the virtual keyword, as in:

    01. //BaseClass02. classA03. {04. publicvirtualvoidshow()05. {06. Console.WriteLine("Hello:BaseClass!");07. Console.ReadLine();08. }09. }10. 11. //DerivedClass12. classB:A13. {14. publicoverridevoidshow()15. {16. Console.WriteLine("Hello:DerivedClass!");

    01 Lotus Notes to SharePoint MigrationUsing QUEST02 Google+ Authentication in ASP.Net

    03 Basics of AngularJS: Part 1

    04 Angular JS Filter, Sorting andAnimation Using MVC and WCF Rest05 How to Retrieve All Users From theGroup in SharePoint Using REST API06 Creating Dynamic DataGridView UsingHelper Class07 Terminologies in MVC: Part 1(ViewData, ViewBag, TempData)08 MVC AngularJS and WCF Rest ServiceFor Mind Reader Quiz09 Angular JS Shopping Cart Using MVCand WCF Rest Service10 Basic Terminology of SQL Server

    View All

    TRENDING UP

    Follow@csharpcorner 14.6Kfollowers

    In Focus MUST READ: Authors How to improve your Writing Skills

    Contribute

    Lotus Notes to SharePoint Migration ... C#CornerSearch

    10946 5 3

    FindusonFacebook

    C#Corner

    87,746peoplelikeC#Corner.

    Like

    TECHNOLOGIES ANSWERS BLOGS VIDEOS INTERVIEWS BOOKS NEWS CHAPTERS CAREER ADVICE JOBS

  • 13/04/2015 VirtualvsOverridevsNewKeywordsinC#

    http://www.csharpcorner.com/UploadFile/2072a9/virtualvsoverridevsnewkeywordsincsharp/ 2/7

    17. Console.ReadLine();18. }19. }

    New Keyword

    The New keyword is also used for polymorphism but in the case of method overriding. So what doesoverriding means? In simple words we can say that we are changing what the base class does for thederived class.

    It is implemented as:

    01. classA02. {03. publicvoidshow()04. {05. Console.WriteLine("Hello:BaseClass!");06. Console.ReadLine();07. }08. }09. 10. classB:A11. {12. publicnewvoidshow()13. {14. Console.WriteLine("Hello:DerivedClass!");15. Console.ReadLine();16. }17. }

    Demo Example

    Sample Implementation

    Here's a simple implementation in C# without using any keywords. Do you think it will run fine, orwill it show a runtime or compiletime errors? Let's see:

    01. usingSystem;02. usingSystem.Collections.Generic;03. usingSystem.Linq;04. usingSystem.Text;05. 06. namespaceGenerics07. {08. classA09. {10. publicvoidshow()11. {12. Console.WriteLine("Hello:BaseClass!");13. Console.ReadLine();14. }15. }16. 17. classB:A18. {19. publicvoidshow()20. {21. Console.WriteLine("Hello:DerivedClass!");22. Console.ReadLine();23. }24. }25. 26. classPolymorphism27. {28. publicstaticvoidMain()29. {30. Aa1=newA();31. a1.show();32. Bb1=newB();33. b1.show();34. Aa2=newB();35. a2.show();36. }37. }38. }

    Output Window

  • 13/04/2015 VirtualvsOverridevsNewKeywordsinC#

    http://www.csharpcorner.com/UploadFile/2072a9/virtualvsoverridevsnewkeywordsincsharp/ 3/7

    It is showing some sort of output. That means there is neither a runtime nor a compiletime error.But it will definitely show a warning in Visual Studio. So do you want to know what it is and how toremove it?

    Keep reading and you will go through that.

    Warning Message

    Here's the warning message that you will get:

    Solution

    The solution of this problem is already in the warning. Just read it carefully and you will get that. Yesyou got that right, for removing that warning we need to use the new keyword.

    In the next sample demo example is showing you a simple demo snippet and implementation of thenew keyword. I hope now you will be getting why we are using the new keyword in here.

    New keyword | Method Overhiding

    Here's a simple snippet of method overriding. So just go through it and guess the output:

    01. usingSystem;02. usingSystem.Collections.Generic;03. usingSystem.Linq;04. usingSystem.Text;05. 06. namespaceGenerics07. {08. classA09. {10. publicvoidshow()11. {12. Console.WriteLine("Hello:BaseClass!");13. Console.ReadLine();14. }15. }16. 17. classB:A18. {19. publicnewvoidshow()20. {21. Console.WriteLine("Hello:DerivedClass!");22. Console.ReadLine();23. }24. }25. 26. classPolymorphism27. {28. publicstaticvoidMain()29. {30. Aa1=newA();31. a1.show();32. Bb1=newB();33. b1.show();34. Aa2=newB();35. a2.show();36. }37. }38. }

  • 13/04/2015 VirtualvsOverridevsNewKeywordsinC#

    http://www.csharpcorner.com/UploadFile/2072a9/virtualvsoverridevsnewkeywordsincsharp/ 4/7

    Output Window

    Explanation

    The procedure goes something like that:

    Virtual and Override Keywords | Method Overriding

    This is a simple example of method overriding. Just go through it and guess the output again andalso try to differentiate between the previous snippet and this snippet.

    01. usingSystem;02. usingSystem.Collections.Generic;03. usingSystem.Linq;04. usingSystem.Text;05. 06. namespaceGenerics07. {08. classA09. {10. publicvirtualvoidshow()11. {12. Console.WriteLine("Hello:BaseClass!");13. Console.ReadLine();14. }15. }16. 17. classB:A18. {19. publicoverridevoidshow()20. {21. Console.WriteLine("Hello:DerivedClass!");22. Console.ReadLine();23. }24. }25. 26. classPolymorphism27. {28. publicstaticvoidMain()29. {30. Aa1=newA();31. a1.show();32. Bb1=newB();33. b1.show();34. Aa2=newB();35. a2.show();36. }37. }38. }

    Output Window

  • 13/04/2015 VirtualvsOverridevsNewKeywordsinC#

    http://www.csharpcorner.com/UploadFile/2072a9/virtualvsoverridevsnewkeywordsincsharp/ 5/7

    Explanation

    The flow goes something like that:

    Overriding + Hiding | Together

    This snippet shows how both of these methods can work together in a same snippet. So just gothrough this and guess the output.

    01. usingSystem;02. usingSystem.Collections.Generic;03. usingSystem.Linq;04. usingSystem.Text;05. 06. namespaceGenerics07. {08. classA09. {10. publicvirtualvoidshow()11. {12. Console.WriteLine("Hello:BaseClass!");13. Console.ReadLine();14. }15. }16. 17. classB:A18. {19. publicoverridevoidshow()20. {21. Console.WriteLine("Hello:DerivedClass!");22. Console.ReadLine();23. }24. }25. 26. classC:B27. {28. publicnewvoidshow()29. {30. Console.WriteLine("AmHere!");31. Console.ReadLine();32. }33. }34. 35. classPolymorphism36. {37. publicstaticvoidMain()38. {39. Aa1=newA();40. a1.show();41. Bb1=newB();42. b1.show();43. Cc1=newC();44. c1.show();45. Aa2=newB();46. a2.show();47. Aa3=newC();48. a3.show();

  • 13/04/2015 VirtualvsOverridevsNewKeywordsinC#

    http://www.csharpcorner.com/UploadFile/2072a9/virtualvsoverridevsnewkeywordsincsharp/ 6/7

    49. Bb3=newC();50. b3.show();51. }52. }53. }

    Output Window

    Explanation

    The flow goes something like that:

    Key Points

    I am providing some key points about these keywords by taking a reference of method overloading andoverriding concepts, since these keywords are used in these mechanisms.

    Virtual and Override

    Used in polymorphism implementationIncludes same method name and same paramsUsed in method overridingIt is also called runtime polymorphismCauses late binding

    New

    It is also used in polymorphism conceptIncludes the same method name and different paramsUsed in method overridingIt is compiletime polymorphismCauses early binding

    Conclusion

    So did you like it, I hope you so!

    Well I tried to provide just a brief sketch of these keywords, that are very necessary for a beginner in C# aswell as in OOP. If you have a good understaind of OOP then you can take any objectoriented language inyour pocket.

    So just go through OOP first and then C# and if you are facing any problem then feel free to ping ormessage me.

    Happy coding, Cheers!

  • 13/04/2015 VirtualvsOverridevsNewKeywordsinC#

    http://www.csharpcorner.com/UploadFile/2072a9/virtualvsoverridevsnewkeywordsincsharp/ 7/7

    RELATED ARTICLES

    Hosted By CBeyond Cloud Services

    2015 C# Corner. All contents are copyright of their authors.

    Abhishek JaiswalAGeek!

    Personal Blog:http://geeksangle.ghost.io/

    Rank42

    1mReaders

    GoldMember

    2Times

    Virtual Method in C# Difference Between Override and New KeywordExplained Step-by-Step

    Difference Between Override and New Keywordin C#

    Var vs Dynamic Keywords in C#Method Overriding in C#

    Function Overriding and Its Impact DuringObject Initialization

    Const vs Readonly in C#Look at Load Testing in Visual Studio 2012

    Differences Among Method Overriding, MethodHiding (new Keyword) and Method Shadowingin C#

    OOPS Concepts and .NET Part 2: Inheritance,Abstraction, & Polymorphism

    COMMENTS 5of5

    Sep 09, 2014

    634 1 0 0 0 Post Reply

    good explanation

    Gyan Parkash

    Sep 09, 2014

    4 12.8k 4.2m 0 0 Post Reply

    Good work Abhishek.

    Dinesh Beniwal

    Sep 09, 2014

    392 268 62.9k 0 0 Post Reply

    nice article

    Manju lata Yadav

    Sep 09, 2014

    325 389 130.5k 0 0 Post Reply

    Good One....

    Divya Sharma

    Sep 09, 2014

    42 3.6k 1m 0 0 Post Reply

    Thank u guys! :)

    Abhishek Jaiswal

    Type your comment here and press Enter Key....

    COMMENT USING

    Facebooksocialplugin

    Addacomment...

    Commentusing...

    MVPs MOST VIEWED LEGENDS NOW PRIZES REVIEWS SURVEY CERTIFICATIONS DOWNLOADS

    CONTACT US PRIVACY POLICY TERMS & CONDITIONS SITEMAP REPORT ABUSE

    PHOTOS CODE SNIPPETS CONSULTING TRAINING STUDENTS MEMBERS MEDIA KIT ABOUT US LINKS IDEAS