Allow with
operator to be used for derived records.
#9589
Replies: 2 comments 3 replies
-
I wonder how something like that might work. Right now |
Beta Was this translation helpful? Give feedback.
-
I like this proposal. It would reduce a lot of boilerplate code that copies all members. Here are some additional notes: Explicitly specify target typeThe original proposal shows: Foo f = new Foo { A = 1, B = 2 };
Bar b = f with { C = 2 }; // does not work currently In this case this is fine but we probably also need the ability to explicitly specify target type. var b = f with<Bar> { C = 2 }; // does not work currently We need such a syntax because we might have the following example situation:
Restrict target typesExplicit slicingAs was already mentioned here we should not allow slicing (only copy some common properties) directly. Baz f = new Baz { A = 1, B = 2, D = 4 };
Bar b = f with { C = 2 }; // disallow this But copying only a subset might still be very relavant. Foo f = new Baz { A = 1, B = 2, D = 4 };
Bar b = f with { C = 2 }; // allow this since we have Foo here
// and
Baz f = new Baz { A = 1, B = 2, D = 4 };
Bar b = (f as Foo) with { C = 2 }; // allow this too Only for inherited typesWe should not allow copying properties with matching names from types that are not inherited. Foo f = new Foo { A = 1 };
Bar b = f with { C = 2 }; // disallow this
public record Foo
{
public required int A { get; init; }
}
public record Bar
{
public required int A { get; init; }
public required int C { get; init; }
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
The
with
operator for use onrecord
types is very handy. What I would like is to be able to use it to create instances of a derived record from a base record instance. See example below.This would essentially just be shorthand for:
Beta Was this translation helpful? Give feedback.
All reactions