KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Possible Duplicate: C# optional parameters on overridden methods This is the output of the following code: Peter: -1 Peter: 0 Fred: 1 Fred: 1 Can you explain me why the call of Peter p.TellYourAge() and p.DoSomething() is not identical? Here the code to try it yourself (VS2010 and FW 4): static void Main(string[] args) { Peter p = new Peter(); p.TellYourAge(); // expected -1, result: -1 p.DoSomething(); // expected -1, result: 0 Fred f = new Fred(); f.TellYourAge(1); // expected 1, result: 1 f.DoSomething(); // expected 1, result: 1 Console.ReadKey(); } } public abstract class Person { public abstract void TellYourAge(int age); // abstract method without default value } public class Peter : Person { public override void TellYourAge(int age = -1) // override with default value { Console.WriteLine("Peter: " + age); } public void DoSomething() { TellYourAge(); } } public class Fred : Person { public override void TellYourAge(int age) // override without default value { Console.WriteLine("Fred: " + age); } public void DoSomething() { TellYourAge(1); } }
Tags (comma-separated)
Save Edits
Cancel