Wednesday, March 19, 2014

Using the new keyword in lieu of the override keyword in C# will allow for method hiding not unlike just leaving the override keyword off.

namespace Whatever.Objects
{
   public class Cat
   {
       public virtual string Speak()
       {
           return "Meow";
       }
   }
}

 
 

Considering the class above, note these three scenarios for a child class named Lion. In each scenario the test provided passes.

Child

Test

 
 namespace Whatever.Objects 
 { 
    public class Lion : Cat 
    { 
        public override string Speak() 
        { 
            return "Roar"; 
        } 
    } 
 } 
 
 
 using Microsoft.VisualStudio.TestTools.UnitTesting; 
 using Whatever.Objects; 
 namespace Whatever.Tests 
 { 
    [TestClass] 
    public class Test 
    { 
        [TestMethod] 
        public void Lion_says_what_youd_expect() 
        { 
            Lion lion = new Lion(); 
            Cat cat = lion; 
            Assert.AreEqual(cat.Speak(), "Roar"); 
        } 
    } 
 } 
 
 
 namespace Whatever.Objects 
 { 
    public class Lion : Cat 
    { 
        public string Speak() 
        { 
            return "Roar"; 
        } 
    } 
 } 
 
 
 using Microsoft.VisualStudio.TestTools.UnitTesting; 
 using Whatever.Objects; 
 namespace Whatever.Tests 
 { 
    [TestClass] 
    public class Test 
    { 
        [TestMethod] 
        public void Lion_says_what_youd_expect() 
        { 
            Lion lion = new Lion(); 
            Cat cat = lion; 
            Assert.AreEqual(cat.Speak(), "Meow"); 
        } 
    } 
 } 
 
 
 namespace Whatever.Objects 
 { 
    public class Lion : Cat 
    { 
        public new string Speak() 
        { 
            return "Roar"; 
        } 
    } 
 } 
 
 
 using Microsoft.VisualStudio.TestTools.UnitTesting; 
 using Whatever.Objects; 
 namespace Whatever.Tests 
 { 
    [TestClass] 
    public class Test 
    { 
        [TestMethod] 
        public void Lion_says_what_youd_expect() 
        { 
            Lion lion = new Lion(); 
            Cat cat = lion; 
            Assert.AreEqual(cat.Speak(), "Meow"); 
        } 
    } 
 } 
 

No comments:

Post a Comment