Calling Overridden Virtual Method from Base Class in C#

I had a serious brain freeze today. I forgot polymorphism 101. I couldn’t remember if a virtual method defined in a base class and called in the constructor of the base class would call the overriden virtual method in a derived class. Instead of ol’reliable (Google Search), I decided to do a quick test because doing beats searching as it kind of burns in a lesson learned for me. Hopefully, I won’t forget this one for awhile. Anyway, the answer is yes, it will call the override and here is a test if you are having a brain freeze too and want to prove it (this is implemented with MSTest).

namespace BrainFreeze
{
	using System;
	using Microsoft.VisualStudio.TestTools.UnitTesting;

	[TestClass]
	public class PolymorphismTest
	{
		[TestMethod]
		public void BaseClassVirtualMethodWhenCalledFromBaseContructorShouldCallDerivedVirtualOverride()
		{
			string expected = "ImpCallVirtual";

			Imp imp = new Imp();
			string actual = imp.Result;

			Assert.AreEqual(expected, actual);
		}

		public class Base
		{
			public Base()
			{
				CallVirtual();
			}

			public string Result { get; set; }

			public virtual void CallVirtual()
			{
				this.Result = "BaseCallVirtual";
			}
		}

		public class Imp : Base
		{
			public Imp()
				: base()
			{
			}

			public override void CallVirtual()
			{
				this.Result = "ImpCallVirtual";
			}
		}
	}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s