Create semantic types in seconds
Install this NuGet package Obviously.SemanticTypes (currently in preview).
The functionality can be easily used.
Declare a partial class and add the attribute SemanticType
.
The only parameter of this attribute is the actual type of the semantic type. Here it is string
.
[SemanticType(typeof(string))]
public partial class EmailAddress { }
⚠ The class must have the
partial
modifier
ℹ The class can besealed
This generator creates
- The public constructor with a single parameter of the actual type
- The implementations of
- the
comparable
andequatable
pattern explicit operator
for the actual type.
- the
ℹ This and the others packages are compile-time dependencies. So the compiled assembly does not contain any references on one of the NuGet packages. Even the
SemanticType
attribute is not in the compiled assembly
For details what is getting generated, see Docs/code_generation.md
The input value of the constructor can be validated.
Therefore a static method named IsValid
has to be implemented.
This method must only have a single parameter of the actual type and must have the return type bool
.
If the value is not valid, an instance of the semantic type cannot be created.
The example shows the validation of an email address.
[SemanticType(typeof(string))]
public partial class EmailAddress
{
public static bool IsValid(string value)
{
return value.Contains('@');
}
}
- Create a fork and make a Pull Request
- Submit a bug
- Submit an idea
- For the inspiration github.com/mperdeck/semantictypes
- For the code generator github.com/AArnott/CodeGeneration.Roslyn
- For the examples github.com/andrewlock/StronglyTypedId
- For making the creation of the generated code so easy github.com/KirillOsenkov/RoslynQuoter
This project is licensed under the MIT License - see the MIT file for details