Calling a virtual method in a constructor: why is it dangerous and how to avoid it?
Hello everyone! I'm a beginner C# developer and I've run into a problem. I'm using ReSharper and noticed it gives a warning: "Virtual member call in a constructor". I have a base class `Animal` and a derived class `Dog`. In the `Animal` constructor, I call the virtual method `Speak()` to set a default name. Here's an example:
```csharp
public class Animal
{
public string Name { get; set; }
public Animal()
{
// ReSharper: Virtual member call in a constructor
InitializeName();
}
public virtual void InitializeName()
{
Name = "Unknown animal";
}
}
public class Dog : Animal
{
public override void InitializeName()
{
Name = "Buddy";
Console.WriteLine("Dog initialized!");
}
}
```
No answers yet.
Log in to leave an answer
Blogs
TypeScript in 2025: Overview of Key Innovations and Features
AI Code Generation in Kotlin: How to Speed Up Development by 2x
How to Write a REST API in Java in 30 Minutes: A Step-by-Step Guide
C# and PostgreSQL: Complete Guide to Integration and Working with Databases