Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Method overriding
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===C#=== [[C Sharp (programming language)|C#]] does support method overriding, but only if explicitly requested using the modifiers {{C sharp|override}} and {{C sharp|virtual}} or {{C sharp|abstract}}. [[File:Csharp method overriding.svg]] <syntaxhighlight lang="csharp"> abstract class Animal { public string Name { get; set; } // Methods public void Drink(); public virtual void Eat(); public void Go(); } class Cat : Animal { public new string Name { get; set; } // Methods public void Drink(); // Warning: hides inherited drink(). Use new public override void Eat(); // Overrides inherited eat(). public new void Go(); // Hides inherited go(). } </syntaxhighlight> When overriding one method with another, the [[Type signature|signatures]] of the two methods must be identical (and with same visibility). In C#, [[class method]]s, [[Indexer (programming)|indexer]]s, [[Property (programming)|properties]] and events can all be overridden. Non-virtual or static methods cannot be overridden. The overridden base method must be ''virtual'', ''abstract'', or ''override''. In addition to the modifiers that are used for method overriding, C# allows the '''hiding''' of an inherited property or method. This is done using the same signature of a property or method but adding the modifier {{C sharp|new}} in front of it.<ref>{{cite web | accessdate = 2011-08-02 | date = 2002-03-25 | first = Hanspeter | last = Mössenböck | pages = 6–8 | publisher = Institut für Systemsoftware, Johannes Kepler Universität Linz, Fachbereich Informatik | title = Advanced C#: Overriding of Methods | quote = | url = http://ssw.jku.at/Teaching/Lectures/CSharp/Tutorial/Part2.pdf}} </ref> In the above example, hiding causes the following: <syntaxhighlight lang="csharp"> Cat cat = new Cat(); cat.Name = …; // accesses Cat.Name cat.Eat(); // calls Cat.Eat() cat.Go(); // calls Cat.Go() ((Animal)cat).Name = …; // accesses Animal.Name! ((Animal)cat).Eat(); // calls Cat.Eat()! ((Animal)cat).Go(); // calls Animal.Go()! </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)