Windows Phone Developers

Saturday, November 15, 2008

How to Override methods in C#

Overriding functions in C#

Methods from base class can be overridden in the derived class and customized for necessity. This means the derived class can contain the member with the same name as that of the parent class

To override a method in the derived class :

  • The base class method must be defined virtual
  • Method in the derived class should be preceded by new or override keywords
  • If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class.
  • If the method in the derived class is preceded with the override keyword, objects of the derived class will call that method instead of the base class method.
  • The base class method can be called from within the derived class using the base keyword.
  • The override, virtual, and new keywords can also be applied to properties, indexers, and events.

class BaseClass

{

virtual public string SayHi()

{

return( "Hi");

}

}

class DerivedClass : BaseClass

{

public override string SayHi()

{

return (base.SayHi() + " from derived");

}

}

If the base class is not declared as virtual, abstract or override, the compiler throws the following error:

'function1' : cannot override inherited member 'function2' because it is not marked "virtual", "abstract", or "override"

A method was overridden that was not explicitly marked as virtual, abstract, or override.

On the other hand, If the override or new keyword is missing the following error will occur

'member1' hides inherited member 'member2'. Use the new keyword if hiding was intended.

A variable was declared with the same name as a variable in a base class. However, the new keyword was not used. This warning informs you that you should use new; the variable is declared as if new had been used in the declaration.

How to access the method in a base class from the derived class

base keyword is used to access members of the base class from within a derived class

return (base.SayHi() + " from derived");

calls the SayHi method of the base class

,

How to override functions in .NET, .NET Function overriding, .NET how to access base class’s method in derived class, base keyword in .NET, virtual methods in .NET, Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

4 comments:

  1. Can I prevent overriding a method for the class I distribute?

    ReplyDelete
  2. Sealed Classes should prevent overriding a method


    http://msdn.microsoft.com/en-us/library/ms173150.aspx

    ReplyDelete
  3. It helped a lot !!! thank you

    ReplyDelete
  4. Its really helpful, can you explain more about new keyword.

    ReplyDelete

kbAlertz.com :: Visual Studio 2005

kbAlertz.com :: Visual Studio 2008

kbAlertz.com :: Visual Basic 2005