Records should allow attributes on the primary constructor #3650
Replies: 8 comments 13 replies
-
Sounds like we need more attribute targets? [constructor: Attr]
public record Rec(
[property: Foo] int X,
[field: NonSerialized] int Y
); |
Beta Was this translation helpful? Give feedback.
-
We had a discussion on the internal mailing list, and the sentiment seemed to be preferring using System;
[AttributeUsage(AttributeTargets.Constructor)]
public class Attr : Attribute{}
public class C {
[method: Attr]
public C()
{
}
} |
Beta Was this translation helpful? Give feedback.
-
Would it make sense that edit to be clear: [method:Attr]
public class Foo { } not just records. Perhaps to implicit constructors only? |
Beta Was this translation helpful? Give feedback.
-
I would not attach such attributes to any explicitly declared constructors within the record. One could argue that such attributes should be attached to the synthesized copy constructor as well as the primary constructor, though. I personally do not see utility in this because I see the copy constructor as an implementation detail of with-expressions that users should not need to customize. |
Beta Was this translation helpful? Give feedback.
-
I think I need this feature to fix an exception I'm getting from System.Text.Json on a record type with secondary constructors: System.NotSupportedException: Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported. |
Beta Was this translation helpful? Give feedback.
-
Is there a github issue or anything where we can track this, or is this discussion the official place for getting news about implementation status? |
Beta Was this translation helpful? Give feedback.
-
Unless I'm missing something, it's the same issue all over again with primary constructors. I started a new discussion for this here. |
Beta Was this translation helpful? Give feedback.
-
I will champion this. I just don't have a proposal yet. |
Beta Was this translation helpful? Give feedback.
-
Slightly related to dotnet/roslyn#44691
Currently there is no way to declare attributes on the primary constructor of a record.
If we decide to allow declaring an explicit "body" for a primary constructor, we could make it so attributes may be applied to that syntax which solely corresponds to the constructor.
Beta Was this translation helpful? Give feedback.
All reactions