C
C#17mo ago
vir_godem

❔ Record help

I've noticed this code doesn't raise any errors:
public record A(int B)
{
public required int B { get; set; }
}
public record A(int B)
{
public required int B { get; set; }
}
Tbh, I tried this because I needed something similar. That is, many of my properties for a class will need B as input for their properties. However, I also want B to be mutable. So I was hoping to achieve that by doing something like the above. I don't see anything like this in the MS Learn documentation on records, so I'm wondering if this case was glossed over or missed, or it should compile properly. And if it does, should I expect property B to be mutable (like I want) or not?
7 Replies
vir_godem
vir_godem17mo ago
Basically, I'm trying to do something like the following, where the AsDouble evaluates the B from the constructor, not the the required property.
public record A(int B)
{
public required int B { get; set; }
public double AsDouble { get; } = (double)B;
}
public record A(int B)
{
public required int B { get; set; }
public double AsDouble { get; } = (double)B;
}
sibber
sibber17mo ago
public double AsDouble { get; } = (double)B; this initializes a readonly property to (double)B thats probably not what you want also AsX are usually methods it was definitely not missed
vir_godem
vir_godem17mo ago
That was just an example tbh. I could replace AsDouble with any other computation. But I want to use the B from the constructor.
sibber
sibber17mo ago
yeah im just telling you what the convention is :) you can see what this gets lowered to here: https://sharplab.io/#v2:D4AQzABATgpgxgeygEwgQQBQEsB2AXCAIQEoBYAKAG8KJaJxoYBHAVy1lVwMIkogHMYeANwQAzkNEBfClKA=
sibber
sibber17mo ago
it actually should warn you if you do this
sibber
sibber17mo ago
so yeah this doesnt get set in the ctor
Accord
Accord17mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.