Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Record types #7

Closed
cphillips83 opened this issue Oct 10, 2023 · 1 comment
Closed

Record types #7

cphillips83 opened this issue Oct 10, 2023 · 1 comment

Comments

@cphillips83
Copy link

cphillips83 commented Oct 10, 2023

[RequireNamedArgs]
public record UserCreate(string Login, string Email)
{
}

How do you apply required params to the ctor created by record types?

@mykolav mykolav closed this as completed in e873acf Nov 9, 2023
@mykolav
Copy link
Owner

mykolav commented Nov 9, 2023

Thank you for the question.

Finally, I got around to looking into it.

The current version 0.0.6 of the NuGet package doesn't support applying [RequireNamedArgs] to a record's primary constructor. I'm uploading an updated package 0.0.7.

Once RequireNamedArgs 0.0.7 is available for download from nuget.org, you can mark a record's primary constructor with [RequireNamedArgs] like in the following example:

// Notice the `AttributeTargets.Class`,  `AttributeTargets.Struct` targets, 
// they tell the compiler, this attribute can be applied to `record` and `record struct`
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Struct)]
class RequireNamedArgsAttribute : Attribute {}


[RequireNamedArgs]
record Character(string Name, int PowerLevel) {}

[RequireNamedArgs]
record struct CharacterStruct(string Name, int PowerLevel) {}

// Elsewhere in your code:
// if the primary constructor of `Character` or `CharacterStruct` is called with positional arguments,
// the analyzer will emit an error.
new Character(Name: "Goku", PowerLevel: 9001);
new CharacterStruct(Name: "Goku", PowerLevel: 9001);

Please note, in the code above the attribute only applies to the primary constructors of the records. If a record has additional constructors, you can mark them with this attribute individually in a normal way.

@mykolav mykolav pinned this issue Nov 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants