seky16
seky16
CC#
Created by seky16 on 12/9/2024 in #help
records, with expression, required property
I'm hitting a strange behaviour and not sure if it's intended. I have the following record definition:
public record Options
{
public required IDataSource DataSource { get; init; }

public int? Take { get; init; } = null;
}
public record Options
{
public required IDataSource DataSource { get; init; }

public int? Take { get; init; } = null;
}
Then I use it in code like this:
var config = new Options() { DataSource = new DataSource(), }
assert(config.DataSource is null) // false
var config2 = config with { Take = null };
assert(config2.DataSource is null); // true
var config3 = config with { Take = null, DataSource = config.DataSource };
assert(config3.DataSource is null); // false
var config = new Options() { DataSource = new DataSource(), }
assert(config.DataSource is null) // false
var config2 = config with { Take = null };
assert(config2.DataSource is null); // true
var config3 = config with { Take = null, DataSource = config.DataSource };
assert(config3.DataSource is null); // false
Why is config2.DataSource null? Is this intended behaviour of combining required and with? If so, shouldn't I get a warning/error that I have an uninitialised required property in config2?
15 replies