├── .gitattributes ├── .github └── workflows │ └── dotnet-core.yml ├── .gitignore ├── LICENSE ├── README.md ├── WrapperValueObject.sln ├── global.json ├── src └── WrapperValueObject.Generator │ ├── AnalyzerReleases.Shipped.md │ ├── AnalyzerReleases.Unshipped.md │ ├── EmbeddedResource.cs │ ├── Generator.GenerationContext.cs │ ├── Generator.cs │ ├── StringExtensions.cs │ ├── WrapperValueObject.Generator.csproj │ ├── resources │ └── WrapperValueObjectAttribute.cs │ └── tools │ ├── install.ps1 │ └── uninstall.ps1 └── test ├── WrapperValueObject.TestConsole ├── Program.cs └── WrapperValueObject.TestConsole.csproj └── WrapperValueObject.Tests ├── CompoundTypes.cs ├── IdTypes.cs ├── MetricTypesTests.cs ├── MoneyTypeTests.cs ├── ProbabilityTypeTests.cs ├── ProductIdTypeTests.cs ├── ScoreTypeTests.cs ├── ValidateTests.cs └── WrapperValueObject.Tests.csproj /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/workflows/dotnet-core.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | tags: '**' 7 | pull_request: 8 | branches: [ master ] 9 | 10 | jobs: 11 | build: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Setup .NET Core 18 | uses: actions/setup-dotnet@v1 19 | with: 20 | dotnet-version: 5.0.102 21 | - name: Install dependencies 22 | run: dotnet restore 23 | - name: Build 24 | run: dotnet build --configuration Release --no-restore 25 | - name: Test 26 | run: dotnet test --no-restore --verbosity normal 27 | - name: Get version 28 | if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') 29 | run: echo "VERSION=$(git describe --tags --dirty)" >> $GITHUB_ENV 30 | - name: Pack 31 | if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') 32 | run: dotnet pack -c Release -o artifacts/ -p:Version=$VERSION 33 | - name: Push 34 | if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') 35 | run: dotnet nuget push artifacts/**.nupkg -s nuget.org --api-key ${{secrets.NUGET_API_KEY}} 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Martin Othamar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WrapperValueObject 2 | 3 | ![Build](https://github.com/martinothamar/WrapperValueObject/workflows/Build/badge.svg) 4 | [![NuGet](https://img.shields.io/nuget/v/WrapperValueObject.Generator.svg)](https://www.nuget.org/packages/WrapperValueObject.Generator/) 5 | 6 | > **Note** 7 | 8 | > This library is not actively maintained at the moment, I recommend looking at [SteveDunn/Vogen](https://github.com/SteveDunn/Vogen) 9 | 10 | A .NET source generator for creating 11 | * Simple value objects wrapping other type(s), without the hassle of manual `Equals`/`GetHashCode` 12 | * Value objects wrapping math primitives and other types 13 | * I.e. `[WrapperValueObject(typeof(int))] readonly partial struct MeterLength { }` - the type is implicitly castable to `int` 14 | * Math and comparison operator overloads are automatically generated 15 | * `ToString` is generated with formatting options similar to those on the primitive type, i.e. `ToString(string? format, IFormatProvider? provider)` for math types 16 | * Strongly typed ID's 17 | * Similar to F# `type ProductId = ProductId of Guid`, here it becomes `[WrapperValueObject] readonly partial struct ProductId { }` with a `New()` function similar to `Guid.NewGuid()` 18 | 19 | The generator targets .NET Standard 2.0 and has been tested with `netcoreapp3.1` and `net5.0` target frameworks. 20 | 21 | Note that record type feature for structs is planned for C# 10, at which point this library might be obsolete. 22 | 23 | ## Installation 24 | 25 | Add to your project file: 26 | 27 | ```xml 28 | 29 | all 30 | runtime; build; native; contentfiles; analyzers 31 | 32 | ``` 33 | 34 | Or install via CLI 35 | 36 | ```sh 37 | dotnet add package WrapperValueObject.Generator --version 0.0.1 38 | ``` 39 | 40 | This package is a build time dependency only. 41 | 42 | ## Usage 43 | 44 | 1. Use the attribute to specify the underlying type. 45 | 2. Declare the struct or class with the `partial` keyword. 46 | 47 | ### Strongly typed ID 48 | 49 | 50 | ```csharp 51 | [WrapperValueObject] readonly partial struct ProductId { } 52 | 53 | var id = ProductId.New(); // Strongly typed Guid wrapper, i.e. {1658db8c-89a4-46ea-b97e-8cf966cfb3f1} 54 | 55 | Assert.NotEqual(ProductId.New(), id); 56 | Assert.False(ProductId.New() == id); 57 | ``` 58 | 59 | ### Money type 60 | 61 | ```csharp 62 | [WrapperValueObject(typeof(decimal))] readonly partial struct Money { } 63 | 64 | Money money = 2m; 65 | 66 | var result = money + 2m; // 4.0 67 | var result2 = money + new Money(2m); 68 | 69 | Assert.True(result == result2); 70 | Assert.Equal(4m, (decimal)result); 71 | ``` 72 | 73 | 74 | ### Metric types 75 | ```csharp 76 | [WrapperValueObject(typeof(int))] 77 | public readonly partial struct MeterLength 78 | { 79 | public static implicit operator CentimeterLength(MeterLength meter) => meter.Value * 100; // .Value is the inner type, in this case int 80 | } 81 | 82 | [WrapperValueObject(typeof(int))] 83 | public readonly partial struct CentimeterLength 84 | { 85 | public static implicit operator MeterLength(CentimeterLength centiMeter) => centiMeter.Value / 100; 86 | } 87 | 88 | MeterLength meters = 2; 89 | 90 | CentimeterLength centiMeters = meters; // 200 91 | 92 | Assert.Equal(200, (int)centiMeters); 93 | ``` 94 | 95 | ### Complex types 96 | 97 | ```csharp 98 | [WrapperValueObject] // Is Guid ID by default 99 | readonly partial struct MatchId { } 100 | 101 | [WrapperValueObject("HomeGoals", typeof(byte), "AwayGoals", typeof(byte))] 102 | readonly partial struct MatchResult { } 103 | 104 | partial struct Match 105 | { 106 | public readonly MatchId MatchId { get; } 107 | 108 | public MatchResult Result { get; private set; } 109 | 110 | public void SetResult(MatchResult result) => Result = result; 111 | 112 | public Match(in MatchId matchId) 113 | { 114 | MatchId = matchId; 115 | Result = default; 116 | } 117 | } 118 | 119 | var match = new Match(MatchId.New()); 120 | 121 | match.SetResult((1, 2)); // Complex types use value tuples underneath, so can be implicitly converted 122 | match.SetResult(new MatchResult(1, 2)); // Or the full constructor 123 | 124 | var otherResult = new MatchResult(2, 1); 125 | 126 | Debug.Assert(otherResult != match.Result); 127 | 128 | match.SetResult((2, 1)); 129 | Debug.Assert(otherResult == match.Result); 130 | 131 | Debug.Assert(match.MatchId != default); 132 | Debug.Assert(match.Result != default); 133 | Debug.Assert(match.Result.HomeGoals == 2); 134 | Debug.Assert(match.Result.AwayGoals == 1); 135 | ``` 136 | 137 | ### Validation 138 | 139 | To make sure only valid instances are created. 140 | The validate function will be called in the generated constructors. 141 | 142 | ```csharp 143 | [WrapperValueObject] // Is Guid ID by default 144 | readonly partial struct MatchId 145 | { 146 | static partial void Validate(Guid id) 147 | { 148 | if (id == Guid.Empty) 149 | throw new ArgumentOutOfRangeException(nameof(id), $"{nameof(id)} must have value"); 150 | } 151 | } 152 | 153 | [WrapperValueObject("HomeGoals", typeof(byte), "AwayGoals", typeof(byte))] 154 | readonly partial struct MatchResult 155 | { 156 | static partial void Validate(byte homeGoals, byte awayGoals) 157 | { 158 | if (homeGoals < 0) 159 | throw new ArgumentOutOfRangeException(nameof(homeGoals), $"{nameof(homeGoals)} value cannot be less than 0"); 160 | if (awayGoals < 0) 161 | throw new ArgumentOutOfRangeException(nameof(awayGoals), $"{nameof(awayGoals)} value cannot be less than 0"); 162 | } 163 | } 164 | ``` 165 | 166 | ## Limitations 167 | 168 | * Need .NET 5 SDK (I think) due to source generators 169 | * Does not support nested types 170 | * Limited configuration options in terms of what code is generated 171 | 172 | ## Related projects and inspiration 173 | 174 | * [StronglyTypedId](https://github.com/andrewlock/StronglyTypedId) by @andrewlock 175 | 176 | ## TODO/under consideration 177 | 178 | Further development on this PoC was prompted by this discussion: https://github.com/ironcev/awesome-roslyn/issues/17 179 | 180 | * Replace one generic attribute (WrapperValueObject) with two (or more) that cleary identify the usecase. E.g. StronglyTypedIdAttribute, ImmutableStructAttribute, ... 181 | * Support everything that StronglyTypedId supports (e.g. optional generation of JSON converters). 182 | * Bring the documentation to the same level as in the StronglyTypedId project. 183 | * Write tests. 184 | * Create Nuget package. 185 | -------------------------------------------------------------------------------- /WrapperValueObject.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30323.103 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WrapperValueObject.Generator", "src\WrapperValueObject.Generator\WrapperValueObject.Generator.csproj", "{D3A17935-A472-440E-B27D-49E1A6852E84}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{B759AFAF-FD91-4FE8-8AA0-420AC3CDDA39}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{33A199CD-5FCA-40DA-8D04-D3510EB7F648}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WrapperValueObject.TestConsole", "test\WrapperValueObject.TestConsole\WrapperValueObject.TestConsole.csproj", "{DE9DA748-672E-4B91-9158-B73EAA7F5CD9}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WrapperValueObject.Tests", "test\WrapperValueObject.Tests\WrapperValueObject.Tests.csproj", "{F7BB7839-9588-42ED-8825-049CB73BDE4B}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {D3A17935-A472-440E-B27D-49E1A6852E84}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {D3A17935-A472-440E-B27D-49E1A6852E84}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {D3A17935-A472-440E-B27D-49E1A6852E84}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {D3A17935-A472-440E-B27D-49E1A6852E84}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {DE9DA748-672E-4B91-9158-B73EAA7F5CD9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {DE9DA748-672E-4B91-9158-B73EAA7F5CD9}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {DE9DA748-672E-4B91-9158-B73EAA7F5CD9}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {DE9DA748-672E-4B91-9158-B73EAA7F5CD9}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {F7BB7839-9588-42ED-8825-049CB73BDE4B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {F7BB7839-9588-42ED-8825-049CB73BDE4B}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {F7BB7839-9588-42ED-8825-049CB73BDE4B}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {F7BB7839-9588-42ED-8825-049CB73BDE4B}.Release|Any CPU.Build.0 = Release|Any CPU 34 | EndGlobalSection 35 | GlobalSection(SolutionProperties) = preSolution 36 | HideSolutionNode = FALSE 37 | EndGlobalSection 38 | GlobalSection(NestedProjects) = preSolution 39 | {D3A17935-A472-440E-B27D-49E1A6852E84} = {B759AFAF-FD91-4FE8-8AA0-420AC3CDDA39} 40 | {DE9DA748-672E-4B91-9158-B73EAA7F5CD9} = {33A199CD-5FCA-40DA-8D04-D3510EB7F648} 41 | {F7BB7839-9588-42ED-8825-049CB73BDE4B} = {33A199CD-5FCA-40DA-8D04-D3510EB7F648} 42 | EndGlobalSection 43 | GlobalSection(ExtensibilityGlobals) = postSolution 44 | SolutionGuid = {3F03858F-70C4-439B-BE1F-FB64588294CB} 45 | EndGlobalSection 46 | EndGlobal 47 | -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "5.0.102", 4 | "rollForward": "latestPatch" 5 | } 6 | } -------------------------------------------------------------------------------- /src/WrapperValueObject.Generator/AnalyzerReleases.Shipped.md: -------------------------------------------------------------------------------- 1 | ; Shipped analyzer releases 2 | ; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md 3 | 4 | -------------------------------------------------------------------------------- /src/WrapperValueObject.Generator/AnalyzerReleases.Unshipped.md: -------------------------------------------------------------------------------- 1 | ; Unshipped analyzer release 2 | ; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md 3 | 4 | ### New Rules 5 | Rule ID | Category | Severity | Notes 6 | --------|----------|----------|------- 7 | WVOG00001 | WrapperValueObject.Generator.Generator | Error | Generator 8 | WVOG00002 | WrapperValueObject.Generator.Generator | Error | Generator 9 | -------------------------------------------------------------------------------- /src/WrapperValueObject.Generator/EmbeddedResource.cs: -------------------------------------------------------------------------------- 1 | // Copyright @kzu 2 | // License MIT 3 | // copied from https://github.com/devlooped/ThisAssembly/blob/main/src/EmbeddedResource.cs 4 | 5 | using System; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Reflection; 9 | 10 | static class EmbeddedResource 11 | { 12 | static readonly string baseDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); 13 | 14 | public static string GetContent(string relativePath) 15 | { 16 | var filePath = Path.Combine(baseDir, Path.GetFileName(relativePath)); 17 | if (File.Exists(filePath)) 18 | return File.ReadAllText(filePath); 19 | 20 | var baseName = Assembly.GetExecutingAssembly().GetName().Name; 21 | var resourceName = relativePath 22 | .TrimStart('.') 23 | .Replace(Path.DirectorySeparatorChar, '.') 24 | .Replace(Path.AltDirectorySeparatorChar, '.'); 25 | 26 | var manifestResourceName = Assembly.GetExecutingAssembly() 27 | .GetManifestResourceNames().FirstOrDefault(x => x.EndsWith(resourceName)); 28 | 29 | if (string.IsNullOrEmpty(manifestResourceName)) 30 | throw new InvalidOperationException($"Did not find required resource ending in '{resourceName}' in assembly '{baseName}'."); 31 | 32 | using var stream = Assembly.GetExecutingAssembly() 33 | .GetManifestResourceStream(manifestResourceName); 34 | 35 | if (stream == null) 36 | throw new InvalidOperationException($"Did not find required resource '{manifestResourceName}' in assembly '{baseName}'."); 37 | 38 | using var reader = new StreamReader(stream); 39 | return reader.ReadToEnd(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/WrapperValueObject.Generator/Generator.GenerationContext.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Text; 3 | using Microsoft.CodeAnalysis; 4 | using Microsoft.CodeAnalysis.CSharp.Syntax; 5 | 6 | namespace WrapperValueObject.Generator 7 | { 8 | public partial class Generator 9 | { 10 | private readonly struct GenerationContext 11 | { 12 | public readonly GeneratorExecutionContext Context; 13 | public readonly StringBuilder SourceBuilder; 14 | public readonly TypeDeclarationSyntax Node; 15 | public readonly ISymbol Type; 16 | public readonly IReadOnlyList<(string Name, INamedTypeSymbol Type)> InnerTypes; 17 | public readonly bool GenerateImplicitConversionToPrimitive; 18 | public readonly bool? GenerateComparisonOperators; 19 | public readonly bool? GenerateMathOperators; 20 | 21 | public GenerationContext( 22 | GeneratorExecutionContext context, 23 | StringBuilder sourceBuilder, 24 | TypeDeclarationSyntax node, 25 | ISymbol type, 26 | IReadOnlyList<(string Name, INamedTypeSymbol Type)> innerTypes, 27 | bool generateImplicitConversionToPrimitive, 28 | bool? generateComparisonOperators, 29 | bool? generateMathOperators 30 | ) 31 | { 32 | Context = context; 33 | SourceBuilder = sourceBuilder; 34 | Node = node; 35 | Type = type; 36 | InnerTypes = innerTypes; 37 | GenerateImplicitConversionToPrimitive = generateImplicitConversionToPrimitive; 38 | GenerateComparisonOperators = generateComparisonOperators; 39 | GenerateMathOperators = generateMathOperators; 40 | } 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/WrapperValueObject.Generator/Generator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Microsoft.CodeAnalysis; 6 | using Microsoft.CodeAnalysis.CSharp; 7 | using Microsoft.CodeAnalysis.CSharp.Syntax; 8 | using Microsoft.CodeAnalysis.Text; 9 | 10 | namespace WrapperValueObject.Generator 11 | { 12 | [Generator] 13 | public partial class Generator : ISourceGenerator 14 | { 15 | private static readonly DiagnosticDescriptor NoNestingRule = new DiagnosticDescriptor( 16 | "WVOG00001", 17 | "Target types for WrapperValueObject generator can't be nested within other types", 18 | "Target types for WrapperValueObject generator can't be nested within other types", 19 | typeof(Generator).FullName, 20 | DiagnosticSeverity.Error, 21 | isEnabledByDefault: true 22 | ); 23 | private static readonly DiagnosticDescriptor MissingPartialModifierRule = new DiagnosticDescriptor( 24 | "WVOG00002", 25 | "Target types for WrapperValueObject generator must be partial", 26 | "Target types for WrapperValueObject generator must be partial", 27 | typeof(Generator).FullName, 28 | DiagnosticSeverity.Error, 29 | isEnabledByDefault: true 30 | ); 31 | 32 | public void Execute(GeneratorExecutionContext context) 33 | { 34 | GenerateAttribute(context); 35 | 36 | var compilation = context.Compilation; 37 | 38 | var sourceBuilder = new StringBuilder(); 39 | 40 | foreach (var tree in compilation.SyntaxTrees) 41 | { 42 | var semanticModel = compilation.GetSemanticModel(tree); 43 | 44 | foreach (var node in tree.GetRoot().DescendantNodesAndSelf().OfType()) 45 | { 46 | ProcessAttributeList(context, node, semanticModel, sourceBuilder); 47 | 48 | sourceBuilder.Clear(); 49 | } 50 | } 51 | 52 | void ProcessAttributeList(GeneratorExecutionContext context, AttributeListSyntax attributeListNode, SemanticModel semanticModel, StringBuilder sourceBuilder) 53 | { 54 | // System.Diagnostics.Debugger.Launch(); 55 | 56 | var attributeNode = attributeListNode.Attributes.SingleOrDefault(a => a.Name.ToString() == "WrapperValueObject"); 57 | if (attributeNode is null) 58 | return; 59 | 60 | var node = (TypeDeclarationSyntax)attributeListNode.Parent!; 61 | 62 | if (node.Parent is ClassDeclarationSyntax) 63 | { 64 | context.ReportDiagnostic(Diagnostic.Create(NoNestingRule, node.GetLocation())); 65 | return; 66 | } 67 | 68 | if (!node.Modifiers.Any(m => m.IsKind(SyntaxKind.PartialKeyword))) 69 | { 70 | context.ReportDiagnostic(Diagnostic.Create(MissingPartialModifierRule, node.GetLocation())); 71 | return; 72 | } 73 | 74 | var type = semanticModel.GetDeclaredSymbol(node); 75 | 76 | List<(string Name, INamedTypeSymbol Type)> innerTypes = new(); 77 | 78 | var currentName = "Value"; 79 | bool generateImplicitConversionToPrimitive = false; 80 | bool? generateComparisonOperators = default; 81 | bool? generateMathOperators = default; 82 | 83 | if (attributeNode.ArgumentList?.Arguments is null) 84 | { 85 | innerTypes.Add(("Value", context.Compilation.GetTypeByMetadataName("System.Guid")!)); 86 | } 87 | else 88 | { 89 | var flag = false; 90 | 91 | foreach (var a in attributeNode.ArgumentList.Arguments) 92 | { 93 | var expression = a.Expression; 94 | 95 | if (expression is TypeOfExpressionSyntax typeOfExpression) 96 | { 97 | // Single type 98 | flag = true; 99 | var typeSymbol = semanticModel.GetSymbolInfo(typeOfExpression.Type).Symbol; 100 | innerTypes.Add((currentName!, (INamedTypeSymbol)typeSymbol!)); 101 | currentName = "Value"; 102 | } 103 | else if (a.NameEquals != null) 104 | { 105 | var id = a.NameEquals.Name.Identifier; 106 | 107 | switch (id.ValueText) 108 | { 109 | case "GenerateImplicitConversionToPrimitive": 110 | generateImplicitConversionToPrimitive = expression.Kind() == SyntaxKind.TrueLiteralExpression; 111 | break; 112 | 113 | case "GenerateComparisonOperators": 114 | generateComparisonOperators = 115 | ((MemberAccessExpressionSyntax)expression).Name.Identifier.ValueText switch 116 | { 117 | "True" => true, 118 | "False" => false, 119 | _ => default(bool?), 120 | }; 121 | break; 122 | 123 | case "GenerateMathOperators": 124 | generateMathOperators = 125 | ((MemberAccessExpressionSyntax)expression).Name.Identifier.ValueText switch 126 | { 127 | "True" => true, 128 | "False" => false, 129 | _ => default(bool?), 130 | }; 131 | break; 132 | 133 | } 134 | } 135 | else 136 | { 137 | // Value tuple config 138 | currentName = (string)semanticModel.GetConstantValue(expression).Value!; 139 | } 140 | } 141 | 142 | if (!flag) 143 | innerTypes.Add(("Value", context.Compilation.GetTypeByMetadataName("System.Guid")!)); 144 | } 145 | 146 | var generationContext = new GenerationContext( 147 | context, 148 | sourceBuilder, 149 | node, 150 | type!, 151 | innerTypes, 152 | generateImplicitConversionToPrimitive, 153 | generateComparisonOperators, 154 | generateMathOperators); 155 | 156 | _ = GenerateWrapper(in generationContext); 157 | } 158 | } 159 | 160 | private void GenerateAttribute(GeneratorExecutionContext context) 161 | { 162 | var attributeSource = EmbeddedResource.GetContent(@"resources/WrapperValueObjectAttribute.cs"); 163 | context.AddSource("WrapperValueObjectAttribute.cs", SourceText.From(attributeSource, Encoding.UTF8)); 164 | } 165 | 166 | private static readonly string[] MathTypes = new[] 167 | { 168 | "System.SByte", 169 | "System.Byte", 170 | "System.Int16", 171 | "System.UInt16", 172 | "System.Int32", 173 | "System.UInt32", 174 | "System.Int64", 175 | "System.UInt64", 176 | "System.Single", 177 | "System.Double", 178 | "System.Decimal", 179 | }; 180 | 181 | private static readonly string[] ByteTypes = new[] 182 | { 183 | "System.SByte", 184 | "System.Byte", 185 | }; 186 | 187 | private bool GenerateWrapper(in GenerationContext context) 188 | { 189 | var isReadOnly = context.Node.Modifiers.Any(m => m.IsKind(SyntaxKind.ReadOnlyKeyword)); 190 | 191 | var innerType = string.Empty; 192 | var isSingleType = context.InnerTypes.Count() == 1; 193 | var isDefaultIdCase = false; 194 | 195 | var implicitConversion = context.GenerateImplicitConversionToPrimitive; 196 | var comparison = context.GenerateComparisonOperators; 197 | var math = context.GenerateMathOperators; 198 | var isNumericType = false; 199 | 200 | if (isSingleType) 201 | { 202 | // If we have 1 type, we might be able to safely generate math operations 203 | var singleType = context.InnerTypes.Single(); 204 | innerType = $"{singleType.Type!.ContainingNamespace}.{singleType.Type.Name}"; 205 | isDefaultIdCase = innerType == "System.Guid"; 206 | 207 | if (MathTypes!.Contains(innerType)) 208 | { 209 | isNumericType = true; 210 | math ??= !context.Type.Name.EndsWith("Id"); 211 | comparison ??= !context.Type.Name.EndsWith("Id"); 212 | } 213 | else 214 | { 215 | comparison = math = false; 216 | } 217 | } 218 | else 219 | { 220 | innerType = context.InnerTypes.Count() == 1 ? "" : $"({string.Join(", ", context.InnerTypes.Select(t => $"{t.Type.ContainingNamespace}.{t.Type.Name}"))})"; 221 | comparison = math = false; 222 | } 223 | 224 | var hasToString = context.Node.Members 225 | .Where(m => m.IsKind(SyntaxKind.MethodDeclaration)) 226 | .Cast() 227 | .Any(m => m.Modifiers.Any(mo => mo.IsKind(SyntaxKind.OverrideKeyword)) && m.Identifier.Text == "ToString" && !m.ParameterList.Parameters.Any()); 228 | 229 | context.SourceBuilder.AppendLine(@$" 230 | using System; 231 | using System.Runtime.CompilerServices; 232 | using System.Runtime.InteropServices; 233 | 234 | #nullable enable 235 | 236 | namespace {context.Type.ContainingNamespace} 237 | {{ 238 | partial {(context.Node is ClassDeclarationSyntax ? "class" : "struct")} {context.Type.Name} : IEquatable<{context.Type.Name}>, IComparable<{context.Type.Name}> 239 | {{ 240 | private readonly {innerType} _value; 241 | "); 242 | 243 | if (isSingleType) 244 | { 245 | context.SourceBuilder.AppendLine(@$" 246 | static partial void Validate({innerType} value); 247 | 248 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 249 | public {context.Type.Name}({innerType} other) 250 | {{ 251 | Validate(other); 252 | _value = other; 253 | }} 254 | "); 255 | } 256 | else 257 | { 258 | var parameters = string.Join(", ", context.InnerTypes.Select((t, i) => $"{t.Type.ContainingNamespace}.{t.Type.Name} {t.Name.FirstCharToLower()}")); 259 | var calls = string.Join(", ", context.InnerTypes.Select((t, i) => t.Name.FirstCharToLower())); 260 | context.SourceBuilder.AppendLine(@$" 261 | static partial void Validate({parameters}); 262 | 263 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 264 | public {context.Type.Name}({innerType} other) 265 | {{ 266 | Validate({string.Join(", ", context.InnerTypes.Select((t, i) => $"other.Item{i + 1}"))}); 267 | _value = other; 268 | }} 269 | 270 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 271 | public {context.Type.Name}({parameters}) 272 | {{ 273 | Validate({calls}); 274 | _value = ({calls}); 275 | }} 276 | "); 277 | } 278 | 279 | context.SourceBuilder.AppendLine(@$" 280 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 281 | public {context.Type.Name}({(isReadOnly ? "in " : "")}{context.Type.Name} other) 282 | {{ 283 | _value = other._value; 284 | }} 285 | 286 | "); 287 | 288 | if (isDefaultIdCase) 289 | { 290 | context.SourceBuilder.AppendLine(@$" 291 | public static {context.Type.Name} New() => Guid.NewGuid(); 292 | "); 293 | } 294 | 295 | if (isSingleType) 296 | { 297 | context.SourceBuilder.AppendLine(@$" 298 | public readonly {innerType} {context.InnerTypes.Single().Name} => _value; 299 | "); 300 | } 301 | else 302 | { 303 | for (int i = 0; i < context.InnerTypes.Count(); i++) 304 | { 305 | var t = context.InnerTypes[i]; 306 | context.SourceBuilder.AppendLine(@$" 307 | public readonly {t.Type.ContainingNamespace}.{t.Type.Name} {t.Name} => _value.Item{i + 1}; 308 | "); 309 | } 310 | } 311 | 312 | context.SourceBuilder.AppendLine(@$" 313 | 314 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 315 | public static implicit operator {context.Type.Name}({innerType} other) => new {context.Type.Name}(other);"); 316 | 317 | if (implicitConversion) 318 | { 319 | context.SourceBuilder.AppendLine(@$" 320 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 321 | public static implicit operator {innerType}({context.Type.Name} other) => other._value;"); 322 | } 323 | else 324 | { 325 | context.SourceBuilder.AppendLine(@$" 326 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 327 | public static explicit operator {innerType}({context.Type.Name} other) => other._value;"); 328 | } 329 | 330 | context.SourceBuilder.AppendLine(@$" 331 | 332 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 333 | public override bool Equals(object? obj) => _value.Equals(obj); 334 | 335 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 336 | public override int GetHashCode() => _value.GetHashCode(); 337 | 338 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 339 | public bool Equals({context.Type.Name} obj) => _value.Equals(obj._value); 340 | 341 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 342 | public int CompareTo({context.Type.Name} value) => _value.CompareTo(value._value); 343 | 344 | "); 345 | 346 | if (isNumericType) 347 | { 348 | context.SourceBuilder.AppendLine(@$" 349 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 350 | public string ToString(IFormatProvider? provider) => _value.ToString(provider); 351 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 352 | public string ToString(string? format) => _value.ToString(format); 353 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 354 | public string ToString(string? format, IFormatProvider? provider) => _value.ToString(format, provider); 355 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 356 | public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default, IFormatProvider? provider = null) 357 | => _value.TryFormat(destination, out charsWritten, format, provider);"); 358 | } 359 | 360 | if (math == true) 361 | { 362 | var isByteType = ByteTypes.Contains(innerType); 363 | 364 | if (isByteType) 365 | { 366 | context.SourceBuilder.AppendLine(@$" 367 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 368 | public static int operator +({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => left._value + right._value; 369 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 370 | public static int operator -({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => left._value - right._value; 371 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 372 | public static int operator /({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => left._value / right._value; 373 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 374 | public static int operator *({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => left._value * right._value; 375 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 376 | public static int operator %({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => left._value % right._value; 377 | "); 378 | } 379 | else 380 | { 381 | context.SourceBuilder.AppendLine(@$" 382 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 383 | public static {context.Type.Name} operator +({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => new {context.Type.Name}(left._value + right._value); 384 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 385 | public static {context.Type.Name} operator -({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => new {context.Type.Name}(left._value - right._value); 386 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 387 | public static {context.Type.Name} operator /({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => new {context.Type.Name}(left._value / right._value); 388 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 389 | public static {context.Type.Name} operator *({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => new {context.Type.Name}(left._value * right._value); 390 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 391 | public static {context.Type.Name} operator %({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => new {context.Type.Name}(left._value % right._value); 392 | "); 393 | } 394 | 395 | } 396 | 397 | if (comparison == true) 398 | { 399 | if (isNumericType) 400 | { 401 | context.SourceBuilder.AppendLine(@$" 402 | 403 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 404 | public static bool operator <({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => left._value < right._value; 405 | 406 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 407 | public static bool operator >({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => left._value > right._value; 408 | 409 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 410 | public static bool operator <=({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => left._value <= right._value; 411 | 412 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 413 | public static bool operator >=({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => left._value >= right._value; 414 | "); 415 | } 416 | else 417 | { 418 | context.SourceBuilder.AppendLine(@$" 419 | 420 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 421 | public static bool operator <({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => left._value.CompareTo(right._value) == -1; 422 | 423 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 424 | public static bool operator >({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => left._value.CompareTo(right._value) == 1; 425 | 426 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 427 | public static bool operator <=({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) 428 | {{ 429 | var result = left._value.CompareTo(right._value); 430 | return result == -1 || result == 0; 431 | }} 432 | 433 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 434 | public static bool operator >=({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) 435 | {{ 436 | var result = left._value.CompareTo(right._value); 437 | return result == 1 || result == 0; 438 | }} 439 | "); 440 | } 441 | } 442 | 443 | if (!hasToString) 444 | { 445 | 446 | context.SourceBuilder.AppendLine(@$" 447 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 448 | public override string ToString() => _value.ToString(); 449 | "); 450 | } 451 | 452 | if (isReadOnly) 453 | { 454 | context.SourceBuilder.AppendLine(@$" 455 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 456 | public bool Equals(in {context.Type.Name} obj) 457 | {{ 458 | return _value.Equals(obj._value); 459 | }} 460 | "); 461 | } 462 | 463 | context.SourceBuilder.AppendLine(@$" 464 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 465 | public static bool operator ==({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => left._value == right._value; 466 | 467 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 468 | public static bool operator !=({(isReadOnly ? "in " : "")}{context.Type.Name} left, {(isReadOnly ? "in " : "")}{context.Type.Name} right) => left._value != right._value; 469 | }}"); 470 | 471 | context.SourceBuilder.AppendLine(@$" 472 | }}"); 473 | 474 | context.Context.AddSource($"{context.Type.Name}_Implementation.cs", SourceText.From(context.SourceBuilder.ToString(), Encoding.UTF8)); 475 | return true; 476 | 477 | static void GenerateSystemTextJsonConverter( 478 | GeneratorExecutionContext context, 479 | StringBuilder sourceBuilder, 480 | TypeDeclarationSyntax node, 481 | ISymbol type, 482 | IEnumerable<(string Name, INamedTypeSymbol Type)> innerTypes 483 | ) 484 | { 485 | 486 | sourceBuilder.AppendLine(@$" 487 | public sealed class {type.Name}JsonConverter 488 | "); 489 | } 490 | } 491 | 492 | public void Initialize(GeneratorInitializationContext context) 493 | { 494 | } 495 | } 496 | } 497 | -------------------------------------------------------------------------------- /src/WrapperValueObject.Generator/StringExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace WrapperValueObject.Generator 2 | { 3 | public static class StringExtensions 4 | { 5 | public static string FirstCharToLower(this string str) 6 | { 7 | return char.ToLowerInvariant(str[0]) + str.Substring(1); 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/WrapperValueObject.Generator/WrapperValueObject.Generator.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | preview 6 | enable 7 | true 8 | 9 | A .NET source generator for creating simple value objects without too much boilerplate for Equals, GetHashCode and operators overloads/implementations. 10 | 11 | MIT 12 | https://github.com/martinothamar/WrapperValueObject 13 | https://github.com/martinothamar/WrapperValueObject 14 | git 15 | false 16 | source-generation source-gen source-generator sourcegenerator value-object C# .NET .NET5 dotnet dotnet5 DDD 17 | Martin Othamar 18 | Copyright 2020 Martin Othamar 19 | true 20 | false 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json ;$(RestoreAdditionalProjectSources) 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /src/WrapperValueObject.Generator/resources/WrapperValueObjectAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace WrapperValueObject 4 | { 5 | [Flags] 6 | public enum WrapperValueObjectJsonConverter 7 | { 8 | None = 0, 9 | NewtonsoftJson = 1, 10 | SystemTextJson = 2, 11 | 12 | All = NewtonsoftJson | SystemTextJson, 13 | } 14 | 15 | public enum TriBool 16 | { 17 | Unset = 0, 18 | True = 1, 19 | False = 2, 20 | } 21 | 22 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)] 23 | public class WrapperValueObjectAttribute : Attribute 24 | { 25 | private readonly (string Name, Type Type)[] _types; 26 | 27 | /// 28 | /// Whether or not to generate the implicit conversion back to 29 | /// an operator. By default, the implicit conversion will not be generated. 30 | /// 31 | public bool GenerateImplicitConversionToPrimitive { get; set; } = false; 32 | 33 | /// 34 | /// Explicitly express whether or not to generate comparison operators. 35 | /// This will be ignored for base types as well as more than one type. 36 | /// If left unset, Comparison operators will be generated as long as 37 | /// the containing struct's name does not end with Id. 38 | /// 39 | public TriBool GenerateComparisonOperators { get; set; } = TriBool.Unset; 40 | 41 | /// 42 | /// Explicitly express whether or not to generate math operators. 43 | /// This will be ignored for base types as well as more than one type. 44 | /// If left unset, Comparison operators will be generated as long as 45 | /// the containing struct's name does not end with Id. 46 | /// 47 | public TriBool GenerateMathOperators { get; set; } = TriBool.Unset; 48 | 49 | /* 50 | /// 51 | /// Which Json Converter(s) to generate, if any. By default, only the System.Text.Json generator 52 | /// will be rendered, but one can be generated for Newtonsoft.Json. 53 | /// 54 | public WrapperValueObjectJsonConverter JsonConverter { get; set; } = WrapperValueObjectJsonConverter.SystemTextJson; 55 | */ 56 | 57 | public WrapperValueObjectAttribute() 58 | : this(typeof(Guid)) 59 | { 60 | } 61 | 62 | public WrapperValueObjectAttribute(Type type) 63 | { 64 | _types = new (string Name, Type Type)[] { ("Value", type) }; 65 | } 66 | 67 | public WrapperValueObjectAttribute(string name1, Type type1) 68 | { 69 | _types = new (string Name, Type Type)[] 70 | { 71 | (name1, type1), 72 | }; 73 | } 74 | 75 | public WrapperValueObjectAttribute(string name1, Type type1, string name2, Type type2) 76 | { 77 | _types = new (string Name, Type Type)[] 78 | { 79 | (name1, type1), 80 | (name2, type2), 81 | }; 82 | } 83 | 84 | public WrapperValueObjectAttribute(string name1, Type type1, string name2, Type type2, string name3, Type type3) 85 | { 86 | _types = new (string Name, Type Type)[] 87 | { 88 | (name1, type1), 89 | (name2, type2), 90 | (name3, type3), 91 | }; 92 | } 93 | 94 | public WrapperValueObjectAttribute(string name1, Type type1, string name2, Type type2, string name3, Type type3, string name4, Type type4) 95 | { 96 | _types = new (string Name, Type Type)[] 97 | { 98 | (name1, type1), 99 | (name2, type2), 100 | (name3, type3), 101 | (name4, type4), 102 | }; 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/WrapperValueObject.Generator/tools/install.ps1: -------------------------------------------------------------------------------- 1 | param($installPath, $toolsPath, $package, $project) 2 | 3 | if($project.Object.SupportsPackageDependencyResolution) 4 | { 5 | if($project.Object.SupportsPackageDependencyResolution()) 6 | { 7 | # Do not install analyzers via install.ps1, instead let the project system handle it. 8 | return 9 | } 10 | } 11 | 12 | $analyzersPaths = Join-Path (Join-Path (Split-Path -Path $toolsPath -Parent) "analyzers") * -Resolve 13 | 14 | foreach($analyzersPath in $analyzersPaths) 15 | { 16 | if (Test-Path $analyzersPath) 17 | { 18 | # Install the language agnostic analyzers. 19 | foreach ($analyzerFilePath in Get-ChildItem -Path "$analyzersPath\*.dll" -Exclude *.resources.dll) 20 | { 21 | if($project.Object.AnalyzerReferences) 22 | { 23 | $project.Object.AnalyzerReferences.Add($analyzerFilePath.FullName) 24 | } 25 | } 26 | } 27 | } 28 | 29 | # $project.Type gives the language name like (C# or VB.NET) 30 | $languageFolder = "" 31 | if($project.Type -eq "C#") 32 | { 33 | $languageFolder = "cs" 34 | } 35 | if($project.Type -eq "VB.NET") 36 | { 37 | $languageFolder = "vb" 38 | } 39 | if($languageFolder -eq "") 40 | { 41 | return 42 | } 43 | 44 | foreach($analyzersPath in $analyzersPaths) 45 | { 46 | # Install language specific analyzers. 47 | $languageAnalyzersPath = join-path $analyzersPath $languageFolder 48 | if (Test-Path $languageAnalyzersPath) 49 | { 50 | foreach ($analyzerFilePath in Get-ChildItem -Path "$languageAnalyzersPath\*.dll" -Exclude *.resources.dll) 51 | { 52 | if($project.Object.AnalyzerReferences) 53 | { 54 | $project.Object.AnalyzerReferences.Add($analyzerFilePath.FullName) 55 | } 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /src/WrapperValueObject.Generator/tools/uninstall.ps1: -------------------------------------------------------------------------------- 1 | param($installPath, $toolsPath, $package, $project) 2 | 3 | if($project.Object.SupportsPackageDependencyResolution) 4 | { 5 | if($project.Object.SupportsPackageDependencyResolution()) 6 | { 7 | # Do not uninstall analyzers via uninstall.ps1, instead let the project system handle it. 8 | return 9 | } 10 | } 11 | 12 | $analyzersPaths = Join-Path (Join-Path (Split-Path -Path $toolsPath -Parent) "analyzers") * -Resolve 13 | 14 | foreach($analyzersPath in $analyzersPaths) 15 | { 16 | # Uninstall the language agnostic analyzers. 17 | if (Test-Path $analyzersPath) 18 | { 19 | foreach ($analyzerFilePath in Get-ChildItem -Path "$analyzersPath\*.dll" -Exclude *.resources.dll) 20 | { 21 | if($project.Object.AnalyzerReferences) 22 | { 23 | $project.Object.AnalyzerReferences.Remove($analyzerFilePath.FullName) 24 | } 25 | } 26 | } 27 | } 28 | 29 | # $project.Type gives the language name like (C# or VB.NET) 30 | $languageFolder = "" 31 | if($project.Type -eq "C#") 32 | { 33 | $languageFolder = "cs" 34 | } 35 | if($project.Type -eq "VB.NET") 36 | { 37 | $languageFolder = "vb" 38 | } 39 | if($languageFolder -eq "") 40 | { 41 | return 42 | } 43 | 44 | foreach($analyzersPath in $analyzersPaths) 45 | { 46 | # Uninstall language specific analyzers. 47 | $languageAnalyzersPath = join-path $analyzersPath $languageFolder 48 | if (Test-Path $languageAnalyzersPath) 49 | { 50 | foreach ($analyzerFilePath in Get-ChildItem -Path "$languageAnalyzersPath\*.dll" -Exclude *.resources.dll) 51 | { 52 | if($project.Object.AnalyzerReferences) 53 | { 54 | try 55 | { 56 | $project.Object.AnalyzerReferences.Remove($analyzerFilePath.FullName) 57 | } 58 | catch 59 | { 60 | 61 | } 62 | } 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /test/WrapperValueObject.TestConsole/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | 4 | namespace WrapperValueObject.TestConsole 5 | { 6 | [WrapperValueObject] 7 | public readonly partial struct MatchId 8 | { 9 | } 10 | 11 | [WrapperValueObject("HomeGoals", typeof(byte), "AwayGoals", typeof(byte))] 12 | public readonly partial struct MatchResult 13 | { 14 | } 15 | 16 | public partial struct Match 17 | { 18 | public readonly MatchId MatchId { get; } 19 | 20 | public MatchResult Result { get; private set; } 21 | 22 | public void SetResult(MatchResult result) => Result = result; 23 | 24 | public Match(in MatchId matchId) 25 | { 26 | MatchId = matchId; 27 | Result = default; 28 | } 29 | } 30 | 31 | public static class Program 32 | { 33 | static void Main() 34 | { 35 | var match = new Match(MatchId.New()); 36 | 37 | match.SetResult((1, 2)); 38 | match.SetResult(new MatchResult(1, 2)); 39 | 40 | var otherResult = new MatchResult(2, 1); 41 | 42 | Debug.Assert(otherResult != match.Result); 43 | 44 | match.SetResult((2, 1)); 45 | Debug.Assert(otherResult == match.Result); 46 | 47 | Debug.Assert(match.MatchId != default); 48 | Debug.Assert(match.Result != default); 49 | Debug.Assert(match.Result.HomeGoals == 2); 50 | Debug.Assert(match.Result.AwayGoals == 1); 51 | 52 | Console.WriteLine("Success!!"); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /test/WrapperValueObject.TestConsole/WrapperValueObject.TestConsole.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net5.0 6 | preview 7 | enable 8 | false 9 | 10 | 11 | 12 | 13 | 14 | 15 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /test/WrapperValueObject.Tests/CompoundTypes.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Xunit; 3 | 4 | namespace WrapperValueObject.Tests 5 | { 6 | [WrapperValueObject("MatchId", typeof(MatchId), "HomeGoals", typeof(byte), "AwayGoals", typeof(byte))] 7 | public readonly partial struct MatchResult 8 | { 9 | } 10 | 11 | public class CompoundTypes 12 | { 13 | [Fact] 14 | public void Test_Compound_Type_Equality() 15 | { 16 | MatchId id = 3; 17 | 18 | MatchResult result = (id, 1, 2); 19 | 20 | Assert.Equal(new MatchResult(id, 1, 2), result); 21 | Assert.Equal(id, result.MatchId); 22 | Assert.Equal(1, result.HomeGoals); 23 | Assert.Equal(2, result.AwayGoals); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /test/WrapperValueObject.Tests/IdTypes.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Xunit; 3 | 4 | namespace WrapperValueObject.Tests 5 | { 6 | [WrapperValueObject(typeof(int))] 7 | public readonly partial struct LeagueId { } 8 | 9 | [WrapperValueObject(typeof(int), GenerateImplicitConversionToPrimitive = true)] 10 | public readonly partial struct MatchId { } 11 | 12 | [WrapperValueObject(typeof(int), GenerateComparisonOperators = TriBool.True, GenerateMathOperators = TriBool.True)] 13 | public readonly partial struct ScoreId { } 14 | 15 | [WrapperValueObject(typeof(int), GenerateComparisonOperators = TriBool.False, GenerateMathOperators = TriBool.False)] 16 | public readonly partial struct NonScore { } 17 | 18 | public class IdTypes 19 | { 20 | [Fact] 21 | public void Test_Basic_Id_Int_Type() 22 | { 23 | LeagueId id1 = 1; 24 | LeagueId id2 = 2; 25 | //LeagueId id3 = id1 + id2; 26 | 27 | Assert.NotEqual(id1, id2); 28 | //Assert.Equal((LeagueId)3, id3); 29 | 30 | //Assert.True(id1 < id2); 31 | //Assert.True(id1 <= id2); 32 | //Assert.False(id1 > id2); 33 | //Assert.False(id1 >= id2); 34 | } 35 | 36 | [Fact] 37 | public void Test_Id_Int_Type_With_Implicit_Conversion() 38 | { 39 | MatchId id1 = 1; 40 | MatchId id2 = 2; 41 | MatchId id3 = id1 + id2; 42 | 43 | Assert.NotEqual(id1, id2); 44 | Assert.Equal((MatchId)3, id3); 45 | 46 | Assert.True(id1 < id2); 47 | Assert.True(id1 <= id2); 48 | Assert.False(id1 > id2); 49 | Assert.False(id1 >= id2); 50 | } 51 | 52 | [Fact] 53 | public void Test_Id_Int_Type_With_Arguments() 54 | { 55 | ScoreId id1 = 1; 56 | ScoreId id2 = 2; 57 | ScoreId id3 = id1 + id2; 58 | 59 | Assert.NotEqual(id1, id2); 60 | Assert.Equal((ScoreId)3, id3); 61 | 62 | Assert.True(id1 < id2); 63 | Assert.True(id1 <= id2); 64 | Assert.False(id1 > id2); 65 | Assert.False(id1 >= id2); 66 | } 67 | 68 | [Fact] 69 | public void Test_Non_Id_Int_Type_With_Arguments() 70 | { 71 | NonScore id1 = 1; 72 | NonScore id2 = 2; 73 | //NonScore id3 = id1 + id2; 74 | 75 | Assert.NotEqual(id1, id2); 76 | //Assert.Equal((NonScore)3, id3); 77 | 78 | //Assert.True(id1 < id2); 79 | //Assert.True(id1 <= id2); 80 | //Assert.False(id1 > id2); 81 | //Assert.False(id1 >= id2); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /test/WrapperValueObject.Tests/MetricTypesTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace WrapperValueObject.Tests 4 | { 5 | [WrapperValueObject(typeof(int))] 6 | public readonly partial struct MeterLength 7 | { 8 | public static implicit operator CentimeterLength(MeterLength meter) => meter.Value * 100; 9 | } 10 | 11 | [WrapperValueObject(typeof(int))] 12 | public readonly partial struct CentimeterLength 13 | { 14 | public static implicit operator MeterLength(CentimeterLength centiMeter) => centiMeter.Value / 100; 15 | } 16 | 17 | public class MetricTypesTests 18 | { 19 | [Fact] 20 | public void Test_Conversion() 21 | { 22 | MeterLength meters = 2; 23 | 24 | CentimeterLength centiMeters = meters; 25 | 26 | Assert.Equal(200, (int)centiMeters); 27 | } 28 | 29 | [Fact] 30 | public void Test_Add() 31 | { 32 | MeterLength meters = 2; 33 | 34 | var result = meters + 2; 35 | 36 | Assert.Equal(((int)meters) + 2, (int)result); 37 | Assert.True(meters != result); 38 | Assert.True(meters == 2); 39 | } 40 | 41 | [Fact] 42 | public void Test_Subtract() 43 | { 44 | MeterLength meters = 5; 45 | 46 | var result = meters - 2; 47 | 48 | Assert.Equal(((int)meters) - 2, (int)result); 49 | Assert.True(meters != result); 50 | Assert.True(meters == 5); 51 | } 52 | 53 | [Fact] 54 | public void Test_Multiply() 55 | { 56 | MeterLength meters = 5; 57 | 58 | var result = meters * 2; 59 | 60 | Assert.Equal(((int)meters) * 2, (int)result); 61 | Assert.True(meters != result); 62 | Assert.True(meters == 5); 63 | } 64 | 65 | [Fact] 66 | public void Test_Divide() 67 | { 68 | MeterLength meters = 2; 69 | 70 | var result = meters / 2; 71 | 72 | Assert.Equal(((int)meters) / 2, (int)result); 73 | Assert.True(meters != result); 74 | Assert.True(meters == 2); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /test/WrapperValueObject.Tests/MoneyTypeTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace WrapperValueObject.Tests 4 | { 5 | [WrapperValueObject(typeof(decimal))] 6 | public readonly partial struct Money 7 | { 8 | } 9 | 10 | public class MoneyTypeTests 11 | { 12 | [Fact] 13 | public void Test_Add() 14 | { 15 | Money money = 2m; 16 | 17 | var result = money + 2m; 18 | var result2 = money + new Money(2m); 19 | 20 | Assert.True(result == result2); 21 | Assert.Equal(((decimal)money) + 2m, (decimal)result); 22 | Assert.True(money != result); 23 | Assert.True(money == 2m); 24 | } 25 | 26 | [Fact] 27 | public void Test_Subtract() 28 | { 29 | Money money = 5m; 30 | 31 | var result = money - 2m; 32 | 33 | Assert.Equal(((decimal)money) - 2m, (decimal)result); 34 | Assert.True(money != result); 35 | Assert.True(money == 5m); 36 | } 37 | 38 | [Fact] 39 | public void Test_Multiply() 40 | { 41 | Money money = 5m; 42 | 43 | var result = money * 2m; 44 | 45 | Assert.Equal(((decimal)money) * 2m, (decimal)result); 46 | Assert.True(money != result); 47 | Assert.True(money == 5m); 48 | } 49 | 50 | [Fact] 51 | public void Test_Divide() 52 | { 53 | Money money = 2m; 54 | 55 | var result = money / 2m; 56 | 57 | Assert.Equal(((decimal)money) / 2m, (decimal)result); 58 | Assert.True(money != result); 59 | Assert.True(money == 2m); 60 | } 61 | 62 | [Fact] 63 | public void Test_Modulo() 64 | { 65 | Money money = 2m; 66 | 67 | var result = money % 2m; 68 | 69 | Assert.Equal(((decimal)money) % 2m, (decimal)result); 70 | Assert.True(money != result); 71 | Assert.True(money == 2m); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /test/WrapperValueObject.Tests/ProbabilityTypeTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace WrapperValueObject.Tests 4 | { 5 | [WrapperValueObject(typeof(double))] 6 | public readonly partial struct Probability 7 | { 8 | } 9 | 10 | public class ProbabilityTypeTests 11 | { 12 | [Fact] 13 | public void Test_Add() 14 | { 15 | Probability probability = 0.9; 16 | 17 | var result = probability + 0.05; 18 | var result2 = probability + new Probability(0.05); 19 | 20 | Assert.True(result == result2); 21 | Assert.Equal(((double)probability) + 0.05, (double)result); 22 | Assert.True(probability != result); 23 | Assert.True(probability == 0.9); 24 | } 25 | 26 | [Fact] 27 | public void Test_Subtract() 28 | { 29 | Probability probability = 0.9; 30 | 31 | var result = probability - 0.05; 32 | var result2 = probability - new Probability(0.05); 33 | 34 | Assert.True(result == result2); 35 | Assert.Equal(((double)probability) - 0.05, (double)result); 36 | Assert.True(probability != result); 37 | Assert.True(probability == 0.9); 38 | } 39 | 40 | [Fact] 41 | public void Test_Multiply() 42 | { 43 | Probability probability = 0.9; 44 | 45 | var result = probability * 0.05; 46 | var result2 = probability * new Probability(0.05); 47 | 48 | Assert.True(result == result2); 49 | Assert.Equal(((double)probability) * 0.05, (double)result); 50 | Assert.True(probability != result); 51 | Assert.True(probability == 0.9); 52 | } 53 | 54 | [Fact] 55 | public void Test_Divide() 56 | { 57 | Probability probability = 0.9; 58 | 59 | var result = probability / 0.05; 60 | var result2 = probability / new Probability(0.05); 61 | 62 | Assert.True(result == result2); 63 | Assert.Equal(((double)probability) / 0.05, (double)result); 64 | Assert.True(probability != result); 65 | Assert.True(probability == 0.9); 66 | } 67 | 68 | [Fact] 69 | public void Test_Modulo() 70 | { 71 | Probability probability = 0.9; 72 | 73 | var result = probability % 0.05; 74 | var result2 = probability % new Probability(0.05); 75 | 76 | Assert.True(result == result2); 77 | Assert.Equal(((double)probability) % 0.05, (double)result); 78 | Assert.True(probability != result); 79 | Assert.True(probability == 0.9); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /test/WrapperValueObject.Tests/ProductIdTypeTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Xunit; 3 | 4 | namespace WrapperValueObject.Tests 5 | { 6 | [WrapperValueObject] readonly partial struct ProductId { } 7 | 8 | public class ProductIdTypeTests 9 | { 10 | [Fact] 11 | public void Test_New() 12 | { 13 | var id = ProductId.New(); 14 | 15 | Assert.NotEqual(Guid.Empty, (Guid)id); 16 | 17 | var id2 = id; 18 | 19 | Assert.Equal(id2, id); 20 | Assert.True(id2 == id); 21 | Assert.NotEqual(ProductId.New(), id); 22 | Assert.True(ProductId.New() != id); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /test/WrapperValueObject.Tests/ScoreTypeTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace WrapperValueObject.Tests 4 | { 5 | [WrapperValueObject(typeof(byte))] 6 | public readonly partial struct Score 7 | { 8 | } 9 | 10 | public class ScoreTypeTests 11 | { 12 | [Fact] 13 | public void Test_Add() 14 | { 15 | Score probability = 10; 16 | 17 | var result = probability + 5; 18 | var result10 = probability + new Score(5); 19 | 20 | Assert.True(result == result10); 21 | Assert.Equal(((byte)probability) + 5, (byte)result); 22 | Assert.True((byte)probability != result); 23 | Assert.True((byte)probability == 10); 24 | } 25 | 26 | [Fact] 27 | public void Test_Subtract() 28 | { 29 | Score probability = 10; 30 | 31 | var result = probability - 5; 32 | var result10 = probability - new Score(5); 33 | 34 | Assert.True(result == result10); 35 | Assert.Equal(((byte)probability) - 5, (byte)result); 36 | Assert.True((byte)probability != result); 37 | Assert.True((byte)probability == 10); 38 | } 39 | 40 | [Fact] 41 | public void Test_Multiply() 42 | { 43 | Score probability = 10; 44 | 45 | var result = probability * 5; 46 | var result10 = probability * new Score(5); 47 | 48 | Assert.True(result == result10); 49 | Assert.Equal(((byte)probability) * 5, (byte)result); 50 | Assert.True((byte)probability != result); 51 | Assert.True((byte)probability == 10); 52 | } 53 | 54 | [Fact] 55 | public void Test_Divide() 56 | { 57 | Score probability = 10; 58 | 59 | var result = probability / 5; 60 | var result10 = probability / new Score(5); 61 | 62 | Assert.True(result == result10); 63 | Assert.Equal(((byte)probability) / 5, (byte)result); 64 | Assert.True((byte)probability != result); 65 | Assert.True((byte)probability == 10); 66 | } 67 | 68 | [Fact] 69 | public void Test_Modulo() 70 | { 71 | Score probability = 10; 72 | 73 | var result = probability % 5; 74 | var result10 = probability % new Score(5); 75 | 76 | Assert.True(result == result10); 77 | Assert.Equal(((byte)probability) % 5, (byte)result); 78 | Assert.True((byte)probability != result); 79 | Assert.True((byte)probability == 10); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /test/WrapperValueObject.Tests/ValidateTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Xunit; 7 | 8 | namespace WrapperValueObject.Tests 9 | { 10 | [WrapperValueObject(typeof(int))] 11 | readonly partial struct ValidateSingleId 12 | { 13 | static partial void Validate(int value) 14 | { 15 | if (value <= 0) 16 | throw new ArgumentOutOfRangeException( 17 | nameof(value), 18 | "Id values cannot be less than 0."); 19 | } 20 | } 21 | 22 | [WrapperValueObject("Id", typeof(int), "Double1", typeof(double))] 23 | readonly partial struct ValidateMultipleId 24 | { 25 | static partial void Validate(int id, double double1) 26 | { 27 | if (id <= 0) 28 | throw new ArgumentOutOfRangeException( 29 | nameof(id), 30 | "Id values cannot be less than 0."); 31 | if (double.IsNaN(double1)) 32 | throw new ArgumentException( 33 | "double1 values cannot be NaN", 34 | nameof(double1)); 35 | } 36 | } 37 | 38 | public class ValidateTests 39 | { 40 | [Fact] 41 | public void ValidateSingleThrowsExceptionLessThanZero() 42 | { 43 | Assert.Throws( 44 | () => (ValidateSingleId)int.MinValue); 45 | Assert.Throws( 46 | () => new ValidateSingleId(0)); 47 | } 48 | 49 | [Fact] 50 | public void ValidateSingleSucceedsOnPositive() 51 | { 52 | var v1 = (ValidateSingleId)1; 53 | Assert.Equal(1, v1); 54 | var v2 = new ValidateSingleId(int.MaxValue); 55 | Assert.Equal(int.MaxValue, v2); 56 | } 57 | 58 | [Fact] 59 | public void ValidateMultipleThrowsExceptionLessThanZero() 60 | { 61 | Assert.Throws( 62 | () => (ValidateMultipleId)(int.MinValue, double.NaN)); 63 | Assert.Throws( 64 | () => new ValidateMultipleId((0, 0d))); 65 | Assert.Throws( 66 | () => (ValidateMultipleId)(1, double.NaN)); 67 | Assert.Throws( 68 | () => new ValidateMultipleId(1, double.NaN)); 69 | } 70 | 71 | [Fact] 72 | public void ValidateMultipleSucceedsOnPositive() 73 | { 74 | var v1 = (ValidateMultipleId)(1, 2d); 75 | Assert.Equal((1, 2d), v1); 76 | var v2 = new ValidateMultipleId(int.MaxValue, double.MinValue); 77 | Assert.Equal((int.MaxValue, double.MinValue), v2); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /test/WrapperValueObject.Tests/WrapperValueObject.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | all 15 | 16 | 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | all 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | --------------------------------------------------------------------------------