CodexBloom - Programming Q&A Platform

Confusion Over Polymorphism with Method Overriding in C# - Unexpected Null Reference Exception

πŸ‘€ Views: 231 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-07
c# oop polymorphism method-overriding csharp

I've looked through the documentation and I'm still confused about Does anyone know how to I'm trying to implement polymorphism in C# using method overriding, but I'm running into a `NullReferenceException` that I can't quite figure out... I have a base class `Animal` with a method `MakeSound()`, and two derived classes `Dog` and `Cat`. My expectation is that when I create an array of `Animal` and call `MakeSound()` on each, the corresponding sound for each animal should be printed. However, I'm getting a `NullReferenceException` on the call to `MakeSound()` of the `Dog` instance. Here's a simplified version of my code: ```csharp public class Animal { public virtual void MakeSound() { Console.WriteLine("Some generic animal sound"); } } public class Dog : Animal { public override void MakeSound() { Console.WriteLine("Bark!"); } } public class Cat : Animal { public override void MakeSound() { Console.WriteLine("Meow!"); } } class Program { static void Main(string[] args) { Animal[] animals = new Animal[2]; animals[0] = new Dog(); // Dog instance animals[1] = null; // Cat instance is missing foreach (var animal in animals) { animal.MakeSound(); // Throws NullReferenceException here } } } ``` I suspect it's because I haven't instantiated the `Cat` class in the array, but I'm unsure if there’s a better way to handle this to avoid the exception. Also, should I have a check for `null` before calling `MakeSound()`? I've read that using interfaces could help in some cases, but I'm not sure how to apply it here. I'm working with .NET 6 and using Visual Studio 2022. Any advice on how to proceed would be greatly appreciated! For reference, this is a production mobile app. I recently upgraded to Csharp 3.10.