With C# 12, we get primary constructors for normal classes.
Consider the following code:
new Derived("XXX").Test();
public class Base(string name)
{
protected void Log() => Console.WriteLine("Base: " + name);
}
public class Derived(string name) : Base(name)
{
public void Test()
{
base.Log();
Console.WriteLine("Derived: " + name);
}
}
This gives the following warning for the string name parameter to the Derived primary constructor:
Program.cs(8,42): Warning CS9107 : Parameter 'string name' is captured into the state of the enclosing type and its value is also passed to the base constructor. The value might be captured by the base class as well.
How can I avoid this warning, should I just squelch it using a pragma? Or is there a better way to avoid it? Is the code written the wrong way? I am not sure I can see an alternative, other than to ditch the primary constructors and rewrite the whole thing to:
new Derived("XXX").Test();
public class Base
{
protected readonly string _name;
protected Base(string name)
{
_name = name;
}
protected void Log() => Console.WriteLine("Base: " + _name);
}
public class Derived : Base
{
public Derived(string name) : base(name) { }
public void Test()
{
base.Log();
Console.WriteLine("Derived: " + base._name);
}
}
Please advise.
Note: This is a contrived example, shortened down from a more complex class hiearchy using the configuration objects from Microsoft.Extensions.Configuration, where multiple levels of classes all need access to the configuration.
Using a property perhaps? You probably want to keep your fields private anyway.