I am currently solving some issue that I have been solving at least five times. Lets have a class like this. This is working solution, but I have to initialize class through parameter in ctor.
public class ArrayBenchmark
{
private readonly int[] _numbers;
public ArrayBenchmark(uint elementCount)
{
_numbers = Enumerable
.Range(0, (int)elementCount)
.Select(_ => new Random().Next(-9, 10))
.ToArray();
}
If I want to use it with parameterless way, it does not work, because the ctor has some priority, so the field is always initialized with the default property value. Code example below.
public class ArrayBenchmark
{
private readonly int[] _numbers;
public uint ElementCount { get; init; } = 1;
public ArrayBenchmark()
{
_numbers = Enumerable
.Range(0, (int)ElementCount)
.Select(_ => new Random().Next(-9, 10))
.ToArray();
}
var benchmarkWith10Elements = new ArrayBenchmark { ElementCount = 10 };
benchmarkWith10Elements.CalculateAllComplexities();
So, is there some way how to fill field parameter from property through parameterless class initialization? Thanks guys
Whaty you want is impossible because the parameterless constructor is called before you initialize the property. This ...
var benchmarkWith10Elements = new ArrayBenchmark { ElementCount = 10 };
is the same code as (syntactic sugar for) ...
var benchmarkWith10Elements = new ArrayBenchmark(); // here ElementCount is 1
benchmarkWith10Elements.ElementCount = 10;
So you need a constructor with an ElementCount
parameter:
public ArrayBenchmark(uint elementCount)
{
ElementCount = elementCount;
_numbers = Enumerable
.Range(0, (int)ElementCount)
.Select(_ => new Random().Next(-9, 10))
.ToArray();
}