Category: .NET Core

RSCG – RossLean.StringificationGenerator

 
 

name RossLean.StringificationGenerator
nuget https://www.nuget.org/packages/RossLean.StringificationGenerator/
link https://github.com/RossLean/RossLean/
author Alex Kalfakakos

Generating constructor code as string

 

This is how you can use RossLean.StringificationGenerator .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="RossLean.StringificationGenerator" Version="1.0.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="RossLean.StringificationGenerator.Core" Version="1.0.0" />
  </ItemGroup>
 
    <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
</Project>

The code that you will use is

1
2
3
4
5
using Code2String;
using RossLean.StringificationGenerator.Generated;
Person person = new Person("Andrei", "Ignat");
string personString = ConstructionCodeGeneration.ForPerson(person);
Console.WriteLine(personString);
1
2
3
4
5
6
7
8
using RossLean.StringificationGenerator.Core;
 
namespace Code2String;
[GenerateConstructionCode]
public record Person(string firstName, string lastName)
{
     
}

 

The code that is generated is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using Code2String;
using RossLean.StringificationGenerator.Core;
using System.Text;
 
namespace RossLean.StringificationGenerator.Generated;
 
public partial class ConstructionCodeGeneration : BaseConstructionCodeGeneration
{
    public static string ForPerson(Person person)
    {
        return $$"""
            new Person({{StringLiteral(person.firstName)}}, {{StringLiteral(person.lastName)}})
            """;
    }
    public static void AppendPerson(Person person, StringBuilder builder)
    {
        builder.Append($$"""
            new Person({{StringLiteral(person.firstName)}}, {{StringLiteral(person.lastName)}})
            """);
    }
    public static string ForPersonTargetTyped(Person person)
    {
        return $$"""
            new({{StringLiteral(person.firstName)}}, {{StringLiteral(person.lastName)}})
            """;
    }
    public static void AppendPersonTargetTyped(Person person, StringBuilder builder)
    {
        builder.Append($$"""
            new({{StringLiteral(person.firstName)}}, {{StringLiteral(person.lastName)}})
            """);
    }
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/RossLean.StringificationGenerator

RSCG – Minerals.AutoInterfaces

 
 

name Minerals.AutoInterfaces
nuget https://www.nuget.org/packages/Minerals.AutoInterfaces/
link https://github.com/SzymonHalucha/Minerals.AutoInterfaces
author Szymon Hałucha

Generating interface from class

 

This is how you can use Minerals.AutoInterfaces .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
 
    <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
 
    <ItemGroup>
      <PackageReference Include="Minerals.AutoInterfaces" Version="0.1.5" />
    </ItemGroup>
</Project>

The code that you will use is

1
2
3
4
5
6
7
8
// See https://aka.ms/new-console-template for more information
using Class2Interface;
 
Console.WriteLine("Hello, World!");
IPerson person=new Person();
person.FirstName="Andrei";
person.LastName="Ignat";
Console.WriteLine(person.FullName());
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
namespace Class2Interface;
[Minerals.AutoInterfaces.GenerateInterface("IPerson")]
public partial class Person:IPerson
{
    public int ID { get; set; }
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public string Name
    {
        get
        {
            return $"{FirstName} {LastName}";
        }
    }
    public string FullName()=>$"{FirstName} {LastName}";
}

 

The code that is generated is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
// <auto-generated>
// This code was generated by a tool.
// Name: Minerals.AutoInterfaces
// Version: 0.1.5+54d6efe308ef06f041fc9b5d9285caeecef3e7c4
// </auto-generated>
#pragma warning disable CS9113
namespace Minerals.AutoInterfaces
{
    [global::System.Diagnostics.DebuggerNonUserCode]
    [global::System.Runtime.CompilerServices.CompilerGenerated]
    [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
    [global::System.AttributeUsage(global::System.AttributeTargets.Class | global::System.AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
    public sealed class GenerateInterfaceAttribute : global::System.Attribute
    {
        public GenerateInterfaceAttribute(string customName = "")
        {
        }
    }
}
#pragma warning restore CS9113
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
// <auto-generated>
// This code was generated by a tool.
// Name: Minerals.AutoInterfaces
// Version: 0.1.5+54d6efe308ef06f041fc9b5d9285caeecef3e7c4
// </auto-generated>
namespace Class2Interface
{
    [global::System.Runtime.CompilerServices.CompilerGenerated]
    public interface IPerson
    {
        int ID { get; set; }
        string? FirstName { get; set; }
        string? LastName { get; set; }
        string Name { get; }
        string FullName();
    }
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/Minerals.AutoInterfaces

RSCG – BitsKit

name BitsKit
nuget https://www.nuget.org/packages/BitsKit/
link https://github.com/barncastle/BitsKit
author barncastle

Reading efficiently from a bit structure

 

This is how you can use BitsKit .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="BitsKit" Version="1.0.0" />
  </ItemGroup>
 
    <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
 
</Project>

The code that you will use is

1
2
3
4
5
using BitsDemo;
 
var z = new zlib_header(0x78, 0x9C);
Console.WriteLine( z.FLEVEL );
Console.WriteLine(z.CM);
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using BitsKit;
using BitsKit.BitFields;
using System.IO.Compression;
 
namespace BitsDemo;
//[BitObject(BitOrder.LeastSignificant)]
//partial struct zlib_header
//{
//    public zlib_header(byte cmf, byte flg)
//    {
//        CMF = cmf;
//        FLG = flg;
//    }
//    [EnumField("CM", 4, typeof(CompressionMode))]
//    [BitField("CINFO", 4)]
//    private byte CMF;
 
//    [BitField("FCHECK", 5)]
//    [BooleanField("FDICT")]
//    [EnumField("FLEVEL", 2, typeof(CompressionLevel))]
//    private byte FLG;
//}
 
[BitObject(BitOrder.LeastSignificant)]
partial struct zlib_header
{
    public zlib_header(byte cmf, byte flg)
    {
        CMF = cmf;
        FLG = flg;
    }
 
    [BitField("CM", 4)]
    [BitField("CINFO", 4)]
    private byte CMF;
 
    [BitField("FCHECK", 5)]
    [BitField("FDICT", 1)]
    [BitField("FLEVEL", 2)]
    private byte FLG;
}

 

The code that is generated is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#nullable enable
#pragma warning disable IDE0005 // Using directive is unnecessary
#pragma warning disable IDE0005_gen // Using directive is unnecessary
#pragma warning disable CS8019  // Unnecessary using directive.
#pragma warning disable IDE0161 // Convert to file-scoped namespace
 
using System;
using System.Runtime.InteropServices;
using BitsKit.Primitives;
 
namespace BitsDemo
{
    partial struct  zlib_header
    {
        public  Byte CM
        {
            get => BitPrimitives.ReadUInt8LSB(CMF, 0, 4);
            set => BitPrimitives.WriteUInt8LSB(ref CMF, 0, value, 4);
        }
 
        public  Byte CINFO
        {
            get => BitPrimitives.ReadUInt8LSB(CMF, 4, 4);
            set => BitPrimitives.WriteUInt8LSB(ref CMF, 4, value, 4);
        }
 
        public  Byte FCHECK
        {
            get => BitPrimitives.ReadUInt8LSB(FLG, 0, 5);
            set => BitPrimitives.WriteUInt8LSB(ref FLG, 0, value, 5);
        }
 
        public  Byte FDICT
        {
            get => BitPrimitives.ReadUInt8LSB(FLG, 5, 1);
            set => BitPrimitives.WriteUInt8LSB(ref FLG, 5, value, 1);
        }
 
        public  Byte FLEVEL
        {
            get => BitPrimitives.ReadUInt8LSB(FLG, 6, 2);
            set => BitPrimitives.WriteUInt8LSB(ref FLG, 6, value, 2);
        }
    }
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/BitsKit

RSCG – FusionReactor

name FusionReactor
nuget https://www.nuget.org/packages/FusionReactor.SourceGenerators.EnumExtensions
link https://github.com/OhFlowi/FusionReactor.SourceGenerators.EnumExtensions
author OhFlowi

Enums to string and other extensions

 

This is how you can use FusionReactor .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
 
  <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="FusionReactor.SourceGenerators.EnumExtensions" Version="1.1.0" />
  </ItemGroup>
 
   
</Project>

The code that you will use is

1
2
3
using EnumClassDemo;
Console.WriteLine(Colors.None.GetName());
Console.WriteLine(ColorsExtensions.GetContent()[Colors.None]);
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
 
namespace EnumClassDemo;
 
//[Flags]
[FusionReactor.SourceGenerators.EnumExtensions.GenerateEnumExtensions]
public enum Colors
{
    [Display(
         ShortName = "None",
         Name = "none - 0",
         Description = "Zero",
         Prompt = "ooF",
         GroupName = "Color1",
         Order = 0)]
    None =0,
    Red=1,
    Green=2,
    Blue=4,
}

 

The code that is generated is

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// <auto-generated />
#nullable enable
using System;
using System.CodeDom.Compiler;
using System.Collections;
#if NET8_0_OR_GREATER
using System.Collections.Frozen;
#endif
using System.Collections.Generic;
using System.Collections.ObjectModel;
 
namespace EnumClassDemo;
/// <summary>
/// Extension methods for the <see cref = "Colors"/> enum.
/// </summary>
[GeneratedCode("FusionReactor.SourceGenerators.EnumExtensions", null)]
public static partial class ColorsExtensions
{
#if NET8_0_OR_GREATER
private static readonly FrozenDictionary<Colors, Int32> content
  = new Dictionary<Colors, Int32>
    {
        { Colors.None, 0 },
{ Colors.Red, 1 },
{ Colors.Green, 2 },
{ Colors.Blue, 4 },
 
    }
    .ToFrozenDictionary();
#else
    private static readonly Dictionary<Colors, Int32> contentDictionary = new Dictionary<Colors, Int32>
    {
        {
            Colors.None,
            0
        },
        {
            Colors.Red,
            1
        },
        {
            Colors.Green,
            2
        },
        {
            Colors.Blue,
            4
        },
    };
    private static readonly IReadOnlyDictionary<Colors, Int32> content = new ReadOnlyDictionary<Colors, Int32>(contentDictionary);
#endif
#if NET8_0_OR_GREATER
private static readonly FrozenSet<string> names = new []
{
    "None",
"Red",
"Green",
"Blue",
 
}
.ToFrozenSet();
#elif NET5_0_OR_GREATER
private static readonly IReadOnlySet<string> names = new HashSet<string>()
{
    "None",
"Red",
"Green",
"Blue",
 
};
#else
    private static readonly HashSet<string> names = new HashSet<string>()
    {
        "None",
        "Red",
        "Green",
        "Blue",
    };
#endif
#if NET8_0_OR_GREATER
private static readonly FrozenSet<Colors> values = new []
{
    Colors.None,
Colors.Red,
Colors.Green,
Colors.Blue,
 
}
.ToFrozenSet();
#elif NET5_0_OR_GREATER
private static readonly IReadOnlySet<Colors> values = new HashSet<Colors>()
{
    Colors.None,
Colors.Red,
Colors.Green,
Colors.Blue,
 
};
#else
    private static readonly HashSet<Colors> values = new HashSet<Colors>()
    {
        Colors.None,
        Colors.Red,
        Colors.Green,
        Colors.Blue,
    };
#endif
    /// <summary>
    /// Gets the content dictionary containing mappings of <see cref = "Colors"/> enum values to values.
    /// </summary>
    /// <returns>The read-only content dictionary.</returns>
     
#if NET8_0_OR_GREATER
public static FrozenDictionary<Colors, Int32> GetContent()
#else
    public static IReadOnlyDictionary<Colors, Int32> GetContent()
#endif
    {
        return content;
    }
 
    /// <summary>
    /// Gets the content dictionary containing mappings of <see cref = "Colors"/> enum values to values.
    /// </summary>
    /// <param name = "enumValue">The enum value for which to get the content dictionary.</param>
    /// <returns>The read-only content dictionary.</returns>
     
#if NET8_0_OR_GREATER
public static FrozenDictionary<Colors, Int32> GetContent(this Colors enumValue)
#else
    public static IReadOnlyDictionary<Colors, Int32> GetContent(this Colors enumValue)
#endif
    {
        return content;
    }
 
    /// <summary>
    /// Retrieves the name of the constant in the <see cref = "Colors"/>.
    /// </summary>
    /// <param name = "enumValue">The enum value to convert.</param>
    /// <returns>
    /// A string containing the name of the <see cref = "Colors"/>;
    /// or <see langword="null"/> if no such constant is found.
    /// </returns>
    public static string? GetName(this Colors enumValue)
    {
        return enumValue switch
        {
            Colors.None => nameof(Colors.None),
            Colors.Red => nameof(Colors.Red),
            Colors.Green => nameof(Colors.Green),
            Colors.Blue => nameof(Colors.Blue),
            _ => null
        };
    }
 
    /// <summary>
    /// Retrieves all available names of the <see cref = "Colors"/>.
    /// </summary>
    /// <returns>An enumerable collection of <see cref = "Colors"/> names.</returns>
     
#if NET8_0_OR_GREATER
public static FrozenSet<string> GetNames()
#elif NET5_0_OR_GREATER
public static IReadOnlySet<string> GetNames()
#else
    public static HashSet<string> GetNames()
#endif
    {
        return names;
    }
 
    /// <summary>
    /// Retrieves all available names of the <see cref = "Colors"/>.
    /// </summary>
    /// <param name = "enumValue">The enumeration value.</param>
    /// <returns>An enumerable collection of <see cref = "Colors"/> names.</returns>
     
#if NET8_0_OR_GREATER
public static FrozenSet<string> GetNames(this Colors enumValue)
#elif NET5_0_OR_GREATER
public static IReadOnlySet<string> GetNames(this Colors enumValue)
#else
    public static HashSet<string> GetNames(this Colors enumValue)
#endif
    {
        return names;
    }
 
    /// <summary>
    /// Retrieves all available values of the <see cref = "Colors"/>.
    /// </summary>
    /// <returns>An enumerable collection of <see cref = "Colors"/> values.</returns>
     
#if NET8_0_OR_GREATER
public static FrozenSet<Colors> GetValues()
#elif NET5_0_OR_GREATER
public static IReadOnlySet<Colors> GetValues()
#else
    public static HashSet<Colors> GetValues()
#endif
    {
        return values;
    }
 
    /// <summary>
    /// Retrieves all available values of the <see cref = "Colors"/>.
    /// </summary>
    /// <param name = "enumValue">The enumeration value.</param>
    /// <returns>An enumerable collection of <see cref = "Colors"/> values.</returns>
     
#if NET8_0_OR_GREATER
public static FrozenSet<Colors> GetValues(this Colors enumValue)
#elif NET5_0_OR_GREATER
public static IReadOnlySet<Colors> GetValues(this Colors enumValue)
#else
    public static HashSet<Colors> GetValues(this Colors enumValue)
#endif
    {
        return values;
    }
 
    /// <summary>
    /// Parses the specified string representation of the enumeration value to its corresponding
    /// <see cref = "Colors"/> value.
    /// </summary>
    /// <param name = "value">A string containing the name or value to convert.</param>
    /// <param name = "ignoreCase">
    /// A boolean indicating whether to ignore case during the parsing. Default is <c>false</c>.
    /// </param>
    /// <returns>
    /// The <see cref = "Colors"/> value equivalent to the specified string representation.
    /// </returns>
    public static Colors Parse(string value, bool ignoreCase = false)
    {
        if (ignoreCase)
        {
            return value.ToLowerInvariant() switch
            {
                "none" => Colors.None,
                "red" => Colors.Red,
                "green" => Colors.Green,
                "blue" => Colors.Blue,
                _ => throw new ArgumentException(),
            };
        }
        else
        {
            return value switch
            {
                "None" => Colors.None,
                "Red" => Colors.Red,
                "Green" => Colors.Green,
                "Blue" => Colors.Blue,
                _ => throw new ArgumentException(),
            };
        }
    }
 
    /// <summary>
    /// Parses the specified string representation of the enumeration value to its corresponding
    /// <see cref = "Colors"/> value.
    /// </summary>
    /// <param name = "enumValue">The current <see cref = "Colors"/> value.</param>
    /// <param name = "value">A string containing the name or value to convert.</param>
    /// <param name = "ignoreCase">
    /// A boolean indicating whether to ignore case during the parsing. Default is <c>false</c>.
    /// </param>
    /// <returns>
    /// The <see cref = "Colors"/> value equivalent to the specified string representation.
    /// </returns>
    public static Colors Parse(this Colors enumValue, string value, bool ignoreCase = false)
    {
        if (ignoreCase)
        {
            return value.ToLowerInvariant() switch
            {
                "none" => Colors.None,
                "red" => Colors.Red,
                "green" => Colors.Green,
                "blue" => Colors.Blue,
                _ => throw new ArgumentException(),
            };
        }
        else
        {
            return value switch
            {
                "None" => Colors.None,
                "Red" => Colors.Red,
                "Green" => Colors.Green,
                "Blue" => Colors.Blue,
                _ => throw new ArgumentException(),
            };
        }
    }
 
    /// <summary>
    /// Tries to parse the specified string representation of an enumeration value to its corresponding
    /// <see cref = "Colors"/> enumeration value.
    /// </summary>
    /// <param name = "value">The string representation of the enumeration value.</param>
    /// <param name = "result">
    /// When this method returns, contains the <see cref = "Colors"/> value equivalent
    /// to the string representation, if the parse succeeded, or default(Colors) if the parse failed.</param>
    /// <returns><c>true</c> if the parsing was successful; otherwise, <c>false</c>.</returns>
    public static bool TryParse(string value, out Colors? result)
    {
        return TryParse(value, false, out result);
    }
 
    /// <summary>
    /// Tries to parse the specified string representation of an enumeration value to its corresponding
    /// <see cref = "Colors"/> enumeration value.
    /// </summary>
    /// <param name = "value">The string representation of the enumeration value.</param>
    /// <param name = "ignoreCase">A boolean indicating whether case should be ignored when parsing.</param>
    /// <param name = "result">
    /// When this method returns, contains the <see cref = "Colors"/> value equivalent
    /// to the string representation, if the parse succeeded, or default(Colors) if the parse failed.</param>
    /// <returns><c>true</c> if the parsing was successful; otherwise, <c>false</c>.</returns>
    public static bool TryParse(string value, bool ignoreCase, out Colors? result)
    {
        if (ignoreCase)
        {
            result = value.ToLowerInvariant() switch
            {
                "none" => Colors.None,
                "red" => Colors.Red,
                "green" => Colors.Green,
                "blue" => Colors.Blue,
                _ => null,
            };
        }
        else
        {
            result = value switch
            {
                "None" => Colors.None,
                "Red" => Colors.Red,
                "Green" => Colors.Green,
                "Blue" => Colors.Blue,
                _ => null,
            };
        }
 
        return result != null;
    }
 
    /// <summary>
    /// Tries to parse the specified string representation of an enumeration value to its corresponding
    /// <see cref = "Colors"/> enumeration value.
    /// </summary>
    /// <param name = "enumValue">The enumeration value to parse.</param>
    /// <param name = "value">The string representation of the enumeration value.</param>
    /// <param name = "result">
    /// When this method returns, contains the <see cref = "Colors"/> value equivalent
    /// to the string representation, if the parse succeeded, or default(Colors) if the parse failed.</param>
    /// <returns><c>true</c> if the parsing was successful; otherwise, <c>false</c>.</returns>
    public static bool TryParse(this Colors enumValue, string value, out Colors? result)
    {
        return TryParse(value, false, out result);
    }
 
    /// <summary>
    /// Tries to parse the specified string representation of an enumeration value to its corresponding
    /// <see cref = "Colors"/> enumeration value.
    /// </summary>
    /// <param name = "enumValue">The enumeration value to parse.</param>
    /// <param name = "value">The string representation of the enumeration value.</param>
    /// <param name = "ignoreCase">A boolean indicating whether case should be ignored when parsing.</param>
    /// <param name = "result">
    /// When this method returns, contains the <see cref = "Colors"/> value equivalent
    /// to the string representation, if the parse succeeded, or default(Colors) if the parse failed.</param>
    /// <returns><c>true</c> if the parsing was successful; otherwise, <c>false</c>.</returns>
    public static bool TryParse(this Colors enumValue, string value, bool ignoreCase, out Colors? result)
    {
        if (ignoreCase)
        {
            result = value.ToLowerInvariant() switch
            {
                "none" => Colors.None,
                "red" => Colors.Red,
                "green" => Colors.Green,
                "blue" => Colors.Blue,
                _ => null,
            };
        }
        else
        {
            result = value switch
            {
                "None" => Colors.None,
                "Red" => Colors.Red,
                "Green" => Colors.Green,
                "Blue" => Colors.Blue,
                _ => null,
            };
        }
 
        return result != null;
    }
}
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
// <auto-generated />
#nullable enable
using System;
using System.Collections;
#if NET8_0_OR_GREATER
using System.Collections.Frozen;
#endif
using System.Collections.Generic;
using System.Collections.ObjectModel;
using FusionReactor.SourceGenerators.EnumExtensions;
 
namespace EnumClassDemo;
public static partial class ColorsExtensions
{
#if !NET8_0_OR_GREATER
    private static readonly Dictionary<Colors, DisplayResult?> displayResultsDictionary = new Dictionary<Colors, DisplayResult?>
    {
        {
            Colors.None,
            new DisplayResult
            {
                ShortName = "None",
                Name = "none - 0",
                Description = "Zero",
                Prompt = "ooF",
                GroupName = "Color1",
                Order = 0,
            }
        },
        {
            Colors.Red,
            null
        },
        {
            Colors.Green,
            null
        },
        {
            Colors.Blue,
            null
        },
    };
#endif
    /// <summary>
    /// Returns the <see cref = "System.ComponentModel.DataAnnotations.DisplayAttribute"/> of the <see cref = "Colors"/> enum.
    /// </summary>
    /// <returns>The display attribute result or the enum value.</returns>
     
#if NET8_0_OR_GREATER
public static FrozenDictionary<Colors, DisplayResult?> DisplayResults
  => new Dictionary<Colors, DisplayResult?>
    {
        { Colors.None, new DisplayResult {ShortName = "None",
Name = "none - 0",
Description = "Zero",
Prompt = "ooF",
GroupName = "Color1",
Order = 0,
}},
{ Colors.Red, null },
{ Colors.Green, null },
{ Colors.Blue, null },
 
    }
    .ToFrozenDictionary();
#else
    public static IReadOnlyDictionary<Colors, DisplayResult?> DisplayResults => new ReadOnlyDictionary<Colors, DisplayResult?>(displayResultsDictionary);
 
#endif
    /// <summary>
    /// Returns the <see cref = "System.ComponentModel.DataAnnotations.DisplayAttribute.ShortName"/> of the <see cref = "Colors"/> enum.
    /// </summary>
    /// <param name = "enumValue">The enum value.</param>
    /// <returns>The display name or the enum value.</returns>
    public static string? DisplayShortName(this Colors enumValue)
    {
        return enumValue switch
        {
            Colors.None => "None",
            Colors.Red => null,
            Colors.Green => null,
            Colors.Blue => null,
            _ => null
        };
    }
 
    /// <summary>
    /// Returns the <see cref = "System.ComponentModel.DataAnnotations.DisplayAttribute.Name"/> of the <see cref = "Colors"/> enum.
    /// </summary>
    /// <param name = "enumValue">The enum value.</param>
    /// <returns>The name or the enum value.</returns>
    public static string? DisplayName(this Colors enumValue)
    {
        return enumValue switch
        {
            Colors.None => "none - 0",
            Colors.Red => null,
            Colors.Green => null,
            Colors.Blue => null,
            _ => null
        };
    }
 
    /// <summary>
    /// Returns the <see cref = "System.ComponentModel.DataAnnotations.DisplayAttribute.Description"/> of the <see cref = "Colors"/> enum.
    /// </summary>
    /// <param name = "enumValue">The enum value.</param>
    /// <returns>The display name or the enum value.</returns>
    public static string? DisplayDescription(this Colors enumValue)
    {
        return enumValue switch
        {
            Colors.None => "Zero",
            Colors.Red => null,
            Colors.Green => null,
            Colors.Blue => null,
            _ => null
        };
    }
 
    /// <summary>
    /// Returns the <see cref = "System.ComponentModel.DataAnnotations.DisplayAttribute.Prompt"/> of the <see cref = "Colors"/> enum.
    /// </summary>
    /// <param name = "enumValue">The enum value.</param>
    /// <returns>The display name or the enum value.</returns>
    public static string? DisplayPrompt(this Colors enumValue)
    {
        return enumValue switch
        {
            Colors.None => "ooF",
            Colors.Red => null,
            Colors.Green => null,
            Colors.Blue => null,
            _ => null
        };
    }
 
    /// <summary>
    /// Returns the <see cref = "System.ComponentModel.DataAnnotations.DisplayAttribute.GroupName"/> of the <see cref = "Colors"/> enum.
    /// </summary>
    /// <param name = "enumValue">The enum value.</param>
    /// <returns>The display name or the enum value.</returns>
    public static string? DisplayGroupName(this Colors enumValue)
    {
        return enumValue switch
        {
            Colors.None => "Color1",
            Colors.Red => null,
            Colors.Green => null,
            Colors.Blue => null,
            _ => null
        };
    }
 
    /// <summary>
    /// Returns the <see cref = "System.ComponentModel.DataAnnotations.DisplayAttribute.Order"/> of the <see cref = "Colors"/> enum.
    /// </summary>
    /// <param name = "enumValue">The enum value.</param>
    /// <returns>The display name or the enum value.</returns>
    public static int? DisplayOrder(this Colors enumValue)
    {
        return enumValue switch
        {
            Colors.None => 0,
            Colors.Red => null,
            Colors.Green => null,
            Colors.Blue => null,
            _ => null
        };
    }
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// <auto-generated />
#nullable enable
using System;
using System.CodeDom.Compiler;
 
namespace FusionReactor.SourceGenerators.EnumExtensions;
/// <inheritdoc cref = "System.ComponentModel.DataAnnotations.DisplayAttribute"/>
[GeneratedCode("FusionReactor.SourceGenerators.EnumExtensions", null)]
public class DisplayResult
{
    /// <summary>
    /// Gets or sets the ShortName attribute property, which may be a resource key string.
    /// </summary>
    public string? ShortName { get; set; }
    /// <summary>
    /// Gets or sets the Name attribute property, which may be a resource key string.
    /// </summary>
    public string? Name { get; set; }
    /// <summary>
    /// Gets or sets the Description attribute property, which may be a resource key string.
    /// </summary>
    public string? Description { get; set; }
    /// <summary>
    /// Gets or sets the Prompt attribute property, which may be a resource key string.
    /// </summary>
    public string? Prompt { get; set; }
    /// <summary>
    /// Gets or sets the GroupName attribute property, which may be a resource key string.
    /// </summary>
    public string? GroupName { get; set; }
    /// <summary>
    /// Gets or sets the order in which this field should be displayed.  If this property is not set then
    /// the presentation layer will automatically determine the order.  Setting this property explicitly
    /// allows an override of the default behavior of the presentation layer.
    /// </summary>
    public int? Order { get; set; }
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
// <auto-generated />
using System;
using System.CodeDom.Compiler;
 
namespace FusionReactor.SourceGenerators.EnumExtensions;
/// <summary>
/// Attribute to mark an enum for FusionReactor.SourceGenerators.EnumExtensions extension generations.
/// </summary>
/// <remarks>
/// This attribute is used to mark an enum for FusionReactor.SourceGenerators.EnumExtensions extension generations.
/// </remarks>
[GeneratedCode("FusionReactor.SourceGenerators.EnumExtensions", null)]
[AttributeUsage(AttributeTargets.Enum)]
public class GenerateEnumExtensionsAttribute : Attribute
{
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/FusionReactor

RSCG – UnionGen

name UnionGen
nuget https://www.nuget.org/packages/UnionGen/
link https://github.com/markushaslinger/union_source_generator
author M. Haslinger

Generating unions between types

 

This is how you can use UnionGen .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
 
    <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
 
    <ItemGroup>
      <PackageReference Include="UnionGen" Version="1.4.0" />
    </ItemGroup>
 
</Project>

The code that you will use is

1
2
3
4
5
6
7
8
9
using UnionTypesDemo;
 
Console.WriteLine("Save or not");
var data = SaveToDatabase.Save(0);
Console.WriteLine(data.IsNotFound);
data = SaveToDatabase.Save(1);
Console.WriteLine(data.IsResultOfInt32);
 
Console.WriteLine(data.AsResultOfInt32());
1
2
3
4
5
6
7
8
using UnionGen.Types;
using UnionGen;
namespace UnionTypesDemo;
 
[Union<Result<int>, NotFound>]
public partial struct ResultSave
{
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
using UnionGen.Types;
 
namespace UnionTypesDemo;
 
public class SaveToDatabase
{
    public static ResultSave Save(int i)
    {
        if(i ==0)
        {
            return new NotFound();
        }
        return new Result<int>(i);
    }
}

 

The code that is generated is

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// <auto-generated by UnionSourceGen />
#nullable enable
using System;
namespace UnionTypesDemo
{
 
    public readonly partial struct ResultSave : IEquatable<ResultSave>
    {
        private readonly UnionGen.Types.Result<int> _value0;
        private readonly UnionGen.Types.NotFound _value1;
        private readonly UnionGen.InternalUtil.StateByte _state;
 
        private ResultSave(int index, int actualTypeIndex)
        {
            _state = new UnionGen.InternalUtil.StateByte(index, actualTypeIndex);
        }
 
        public ResultSave(UnionGen.Types.Result<int> value): this(0, 0)
        {
            _value0 = value;
        }
 
        public ResultSave(UnionGen.Types.NotFound value): this(1, 1)
        {
            _value1 = value;
        }
 
        [Obsolete(UnionGen.InternalUtil.UnionGenInternalConst.DefaultConstructorWarning, true)]
        public ResultSave(): this(0, 0) {}
 
        public bool IsResultOfInt32 => _state.Index == 0;
        public bool IsNotFound => _state.Index == 1;
 
        public UnionGen.Types.Result<int> AsResultOfInt32() =>
            IsResultOfInt32
                ? _value0
                : throw UnionGen.InternalUtil.ExceptionHelper.ThrowNotOfType(GetTypeName(0), GetTypeName(_state.ActualTypeIndex));
         
        public UnionGen.Types.NotFound AsNotFound() =>
            IsNotFound
                ? _value1
                : throw UnionGen.InternalUtil.ExceptionHelper.ThrowNotOfType(GetTypeName(1), GetTypeName(_state.ActualTypeIndex));
 
        public static implicit operator ResultSave(UnionGen.Types.Result<int> value) => new ResultSave(value);
        public static implicit operator ResultSave(UnionGen.Types.NotFound value) => new ResultSave(value);
        public static bool operator ==(ResultSave left, ResultSave right) => left.Equals(right);
        public static bool operator !=(ResultSave left, ResultSave right) => !left.Equals(right);
 
        public TResult Match<TResult>(Func<UnionGen.Types.Result<int>, TResult> withResultOfInt32, Func<UnionGen.Types.NotFound, TResult> withNotFound) =>      
            _state.ActualTypeIndex switch
            {
                0 => withResultOfInt32(_value0),
                1 => withNotFound(_value1),
                _ => throw UnionGen.InternalUtil.ExceptionHelper.ThrowUnknownTypeIndex(_state.ActualTypeIndex)
            };
 
        public void Switch(Action<UnionGen.Types.Result<int>> forResultOfInt32, Action<UnionGen.Types.NotFound> forNotFound)     
        {
            switch (_state.ActualTypeIndex)
            {
                case 0: forResultOfInt32(_value0); break;
                case 1: forNotFound(_value1); break;
                default: throw UnionGen.InternalUtil.ExceptionHelper.ThrowUnknownTypeIndex(_state.ActualTypeIndex);
            }
        }
 
        public override string ToString() =>        
            _state.Index switch
            {
                0 => _value0.ToString()!,
                1 => _value1.ToString()!,
                _ => throw UnionGen.InternalUtil.ExceptionHelper.ThrowUnknownTypeIndex(_state.Index)
            };
 
        public bool Equals(ResultSave other) =>
            _state.Index == other._state.Index
                && _state.Index switch
                {
                    0 => _value0.Equals(other._value0),
                    1 => _value1.Equals(other._value1),
                    _ => false
                };
 
        public override bool Equals(object? obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }
            return obj is ResultSave other && Equals(other);
        }
 
        public override int GetHashCode(){     
            unchecked
            {
                var hash = _state.Index switch
                {
                    0 => _value0.GetHashCode(),
                    1 => _value1.GetHashCode(),
                    _ => 0
                };
                return (hash * 397) ^ _state.Index;
            }
        }
 
        public string GetTypeName(int index) =>
            index switch
            {
                0 => "UnionGen.Types.Result<int>",
                1 => "UnionGen.Types.NotFound",
                _ => throw UnionGen.InternalUtil.ExceptionHelper.ThrowUnknownTypeIndex(index)
            };
 
    }
 
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/UnionGen

RSCG – EnumUtilities

name EnumUtilities
nuget https://www.nuget.org/packages/Raiqub.Generators.EnumUtilities/
link https://github.com/skarllot/EnumUtilities
author Fabricio Godoy

Enum to string- and multiple other extensions for an enum

 

This is how you can use EnumUtilities .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
 
  <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="Raiqub.Generators.EnumUtilities" Version="1.6.14" />
  </ItemGroup>
</Project>

The code that you will use is

1
2
3
using EnumClassDemo;
Console.WriteLine(Colors.None.ToStringFast());
Console.WriteLine(Colors.None.ToEnumMemberValue());
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
using Raiqub.Generators.EnumUtilities;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
 
namespace EnumClassDemo;
[EnumGenerator]
[Flags]
//[JsonConverterGenerator]
//[JsonConverter(typeof(ColorJsonConverter))]
public enum Colors
{
    //[Display(ShortName = "This should be never seen")]
    [EnumMember(Value = "This should be never seen")]
    None =0,
    Red=1,
    Green=2,
    Blue=4,
}

 

The code that is generated is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// <auto-generated />
#nullable enable
 
using System;
using System.Runtime.CompilerServices;
using System.Threading;
 
#pragma warning disable CS1591 // publicly visible type or member must be documented
 
namespace EnumClassDemo
{
    [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Raiqub.Generators.EnumUtilities", "1.6.0.0")]
    public static partial class ColorsExtensions
    {
        /// <summary>Converts the value of this instance to its equivalent string representation.</summary>
        /// <returns>The string representation of the value of this instance.</returns>
        public static string ToStringFast(this Colors value)
        {
            return value switch
            {
                Colors.None => nameof(Colors.None),
                Colors.Red => nameof(Colors.Red),
                Colors.Green => nameof(Colors.Green),
                Colors.Blue => nameof(Colors.Blue),
                _ => value.ToString()
            };
        }
 
        /// <summary>Returns a boolean telling whether the value of this instance exists in the enumeration.</summary>
        /// <returns><c>true</c> if the value of this instance exists in the enumeration; <c>false</c> otherwise.</returns>
        public static bool IsDefined(this Colors value)
        {
            return ColorsValidation.IsDefined(value);
        }
 
    #if NET5_0_OR_GREATER
        /// <summary>Bitwise "ands" two enumerations and replaces the first value with the result, as an atomic operation.</summary>
        /// <param name="location">A variable containing the first value to be combined.</param>
        /// <param name="value">The value to be combined with the value at <paramref name="location" />.</param>
        /// <returns>The original value in <paramref name="location" />.</returns>
        public static Colors InterlockedAnd(this ref Colors location, Colors value)
        {
            ref int locationRaw = ref Unsafe.As<Colors, int>(ref location);
            int resultRaw = Interlocked.And(ref locationRaw, Unsafe.As<Colors, int>(ref value));
            return Unsafe.As<int, Colors>(ref resultRaw);
        }
 
        /// <summary>Bitwise "ors" two enumerations and replaces the first value with the result, as an atomic operation.</summary>
        /// <param name="location">A variable containing the first value to be combined.</param>
        /// <param name="value">The value to be combined with the value at <paramref name="location" />.</param>
        /// <returns>The original value in <paramref name="location" />.</returns>
        public static Colors InterlockedOr(this ref Colors location, Colors value)
        {
            ref int locationRaw = ref Unsafe.As<Colors, int>(ref location);
            int resultRaw = Interlocked.Or(ref locationRaw, Unsafe.As<Colors, int>(ref value));
            return Unsafe.As<int, Colors>(ref resultRaw);
        }
    #endif
 
        /// <summary>Compares two enumerations for equality and, if they are equal, replaces the first value.</summary>
        /// <param name="location">The destination, whose value is compared with <paramref name="comparand" /> and possibly replaced.</param>
        /// <param name="value">The value that replaces the destination value if the comparison results in equality.</param>
        /// <param name="comparand">The value that is compared to the value at <paramref name="location" />.</param>
        /// <returns>The original value in <paramref name="location" />.</returns>
        public static Colors InterlockedCompareExchange(this ref Colors location, Colors value, Colors comparand)
        {
            ref int locationRaw = ref Unsafe.As<Colors, int>(ref location);
            int resultRaw = Interlocked.CompareExchange(ref locationRaw, Unsafe.As<Colors, int>(ref value), Unsafe.As<Colors, int>(ref comparand));
            return Unsafe.As<int, Colors>(ref resultRaw);
        }
 
        /// <summary>Sets an enumeration value to a specified value and returns the original value, as an atomic operation.</summary>
        /// <param name="location">The variable to set to the specified value.</param>
        /// <param name="value">The value to which the <paramref name="location" /> parameter is set.</param>
        /// <returns>The original value of <paramref name="location" />.</returns>
        public static Colors InterlockedExchange(this ref Colors location, Colors value)
        {
            ref int locationRaw = ref Unsafe.As<Colors, int>(ref location);
            int resultRaw = Interlocked.Exchange(ref locationRaw, Unsafe.As<Colors, int>(ref value));
            return Unsafe.As<int, Colors>(ref resultRaw);
        }
 
        public static string ToEnumMemberValue(this Colors value)
        {
            return value switch
            {
                Colors.None => "This should be never seen",
                Colors.Red => nameof(Colors.Red),
                Colors.Green => nameof(Colors.Green),
                Colors.Blue => nameof(Colors.Blue),
                _ => value.ToString()
            };
        }
    }
}
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// <auto-generated />
#nullable enable
 
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
 
#pragma warning disable CS1591 // publicly visible type or member must be documented
 
namespace EnumClassDemo
{
    [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Raiqub.Generators.EnumUtilities", "1.6.0.0")]
    public static partial class ColorsFactory
    {
        /// <summary>
        /// Converts the string representation of the name or numeric value of one or more enumerated constants to
        /// an equivalent enumerated object. The return value indicates whether the conversion succeeded.
        /// </summary>
        /// <param name="name">The case-sensitive string representation of the enumeration name or underlying value to convert.</param>
        /// <param name="comparisonType">One of the enumeration values that specifies how the strings will be compared.</param>
        /// <param name="result">
        /// When this method returns, result contains an object of type Colors whose value is represented by value
        /// if the parse operation succeeds. If the parse operation fails, result contains the default value of the
        /// underlying type of Colors. Note that this value need not be a member of the Colors enumeration.
        /// </param>
        /// <returns><c>true</c> if the value parameter was converted successfully; otherwise, <c>false</c>.</returns>
        /// <exception cref="ArgumentException"><paramref name="comparisonType"/> is not a <see cref="StringComparison"/> value.</exception>
        public static bool TryParse(
            [NotNullWhen(true)] string? name,
            StringComparison comparisonType,
            out Colors result)
        {
            switch (name)
            {
                case { } s when s.Equals(nameof(Colors.None), comparisonType):
                    result = Colors.None;
                    return true;
                case { } s when s.Equals(nameof(Colors.Red), comparisonType):
                    result = Colors.Red;
                    return true;
                case { } s when s.Equals(nameof(Colors.Green), comparisonType):
                    result = Colors.Green;
                    return true;
                case { } s when s.Equals(nameof(Colors.Blue), comparisonType):
                    result = Colors.Blue;
                    return true;
                case { } s when TryParseNumeric(s, comparisonType, out int val):
                    result = (Colors)val;
                    return true;
                default:
                    return Enum.TryParse(name, out result);
            }
        }
 
        /// <summary>
        /// Converts the string representation of the name or numeric value of one or more enumerated constants to
        /// an equivalent enumerated object. The return value indicates whether the conversion succeeded.
        /// </summary>
        /// <param name="name">The case-sensitive string representation of the enumeration name or underlying value to convert.</param>
        /// <param name="result">
        /// When this method returns, result contains an object of type Colors whose value is represented by value
        /// if the parse operation succeeds. If the parse operation fails, result contains the default value of the
        /// underlying type of Colors. Note that this value need not be a member of the Colors enumeration.
        /// </param>
        /// <returns><c>true</c> if the value parameter was converted successfully; otherwise, <c>false</c>.</returns>
        public static bool TryParse(
            [NotNullWhen(true)] string? name,
            out Colors result)
        {
            switch (name)
            {
                case nameof(Colors.None):
                    result = Colors.None;
                    return true;
                case nameof(Colors.Red):
                    result = Colors.Red;
                    return true;
                case nameof(Colors.Green):
                    result = Colors.Green;
                    return true;
                case nameof(Colors.Blue):
                    result = Colors.Blue;
                    return true;
                case { } s when TryParseNumeric(s, StringComparison.Ordinal, out int val):
                    result = (Colors)val;
                    return true;
                default:
                    return Enum.TryParse(name, out result);
            }
        }
 
        /// <summary>
        /// Converts the string representation of the name or numeric value of one or more enumerated constants to
        /// an equivalent enumerated object. The return value indicates whether the conversion succeeded.
        /// </summary>
        /// <param name="name">The case-sensitive string representation of the enumeration name or underlying value to convert.</param>
        /// <param name="result">
        /// When this method returns, result contains an object of type Colors whose value is represented by value
        /// if the parse operation succeeds. If the parse operation fails, result contains the default value of the
        /// underlying type of Colors. Note that this value need not be a member of the Colors enumeration.
        /// </param>
        /// <returns><c>true</c> if the value parameter was converted successfully; otherwise, <c>false</c>.</returns>
        public static bool TryParseIgnoreCase(
            [NotNullWhen(true)] string? name,
            out Colors result)
        {
            return TryParse(name, StringComparison.OrdinalIgnoreCase, out result);
        }
 
        /// <summary>
        /// Converts the string representation of the name or numeric value of one or more enumerated constants to
        /// an equivalent enumerated object.
        /// </summary>
        /// <param name="name">The case-sensitive string representation of the enumeration name or underlying value to convert.</param>
        /// <returns>
        /// Contains an object of type Colors whose value is represented by value if the parse operation succeeds.
        /// If the parse operation fails, result contains <c>null</c> value.
        /// </returns>
        public static Colors? TryParse(string? name)
        {
            return TryParse(name, out Colors result) ? result : null;
        }
 
        /// <summary>
        /// Converts the string representation of the name or numeric value of one or more enumerated constants to
        /// an equivalent enumerated object.
        /// </summary>
        /// <param name="name">The case-sensitive string representation of the enumeration name or underlying value to convert.</param>
        /// <returns>
        /// Contains an object of type Colors whose value is represented by value if the parse operation succeeds.
        /// If the parse operation fails, result contains <c>null</c> value.
        /// </returns>
        public static Colors? TryParseIgnoreCase(string? name)
        {
            return TryParse(name, StringComparison.OrdinalIgnoreCase, out Colors result) ? result : null;
        }
 
        /// <summary>
        /// Converts the string representation of the name or numeric value of one or more enumerated constants to
        /// an equivalent enumerated object.
        /// </summary>
        /// <param name="name">The case-sensitive string representation of the enumeration name or underlying value to convert.</param>
        /// <param name="comparisonType">One of the enumeration values that specifies how the strings will be compared.</param>
        /// <returns>
        /// Contains an object of type Colors whose value is represented by value if the parse operation succeeds.
        /// If the parse operation fails, result contains <c>null</c> value.
        /// </returns>
        /// <exception cref="ArgumentException"><paramref name="comparisonType"/> is not a <see cref="StringComparison"/> value.</exception>
        public static Colors? TryParse(string? name, StringComparison comparisonType)
        {
            return TryParse(name, comparisonType, out Colors result) ? result : null;
        }
 
        /// <summary>
        /// Converts the string representation of the value associated with one enumerated constant to
        /// an equivalent enumerated object. The return value indicates whether the conversion succeeded.
        /// </summary>
        /// <param name="enumMemberValue">The value as defined with <see cref="System.Runtime.Serialization.EnumMemberAttribute"/>.</param>
        /// <param name="comparisonType">One of the enumeration values that specifies how the strings will be compared.</param>
        /// <param name="result">
        /// When this method returns, result contains an object of type Colors whose value is represented by value
        /// if the parse operation succeeds. If the parse operation fails, result contains the default value of the
        /// underlying type of Colors. Note that this value need not be a member of the Colors enumeration.
        /// </param>
        /// <returns><c>true</c> if the value parameter was converted successfully; otherwise, <c>false</c>.</returns>
        /// <exception cref="ArgumentException"><paramref name="comparisonType"/> is not a <see cref="StringComparison"/> value.</exception>
        public static bool TryParseFromEnumMemberValue(
            [NotNullWhen(true)] string? enumMemberValue,
            StringComparison comparisonType,
            out Colors result)
        {
            switch (enumMemberValue)
            {
                case { } s when s.Equals("This should be never seen", comparisonType):
                    result = Colors.None;
                    return true;
                case { } s when s.Equals(nameof(Colors.Red), comparisonType):
                    result = Colors.Red;
                    return true;
                case { } s when s.Equals(nameof(Colors.Green), comparisonType):
                    result = Colors.Green;
                    return true;
                case { } s when s.Equals(nameof(Colors.Blue), comparisonType):
                    result = Colors.Blue;
                    return true;
                default:
                    result = default;
                    return false;
            }
        }
 
        /// <summary>
        /// Converts the string representation of the value associated with one enumerated constant to
        /// an equivalent enumerated object. The return value indicates whether the conversion succeeded.
        /// </summary>
        /// <param name="enumMemberValue">The value as defined with <see cref="System.Runtime.Serialization.EnumMemberAttribute"/>.</param>
        /// <param name="result">
        /// When this method returns, result contains an object of type Colors whose value is represented by value
        /// if the parse operation succeeds. If the parse operation fails, result contains the default value of the
        /// underlying type of Colors. Note that this value need not be a member of the Colors enumeration.
        /// </param>
        /// <returns><c>true</c> if the value parameter was converted successfully; otherwise, <c>false</c>.</returns>
        public static bool TryParseFromEnumMemberValue([NotNullWhen(true)] string? enumMemberValue, out Colors result)
        {
            return TryParseFromEnumMemberValue(enumMemberValue, StringComparison.Ordinal, out result);
        }
 
        /// <summary>
        /// Converts the string representation of the value associated with one enumerated constant to
        /// an equivalent enumerated object.
        /// </summary>
        /// <param name="enumMemberValue">The value as defined with <see cref="System.Runtime.Serialization.EnumMemberAttribute"/>.</param>
        /// <param name="comparisonType">One of the enumeration values that specifies how the strings will be compared.</param>
        /// <returns>
        /// Contains an object of type Colors whose value is represented by value if the parse operation succeeds.
        /// If the parse operation fails, result contains a null value.
        /// </returns>
        /// <exception cref="ArgumentException"><paramref name="comparisonType"/> is not a <see cref="StringComparison"/> value.</exception>
        public static Colors? TryParseFromEnumMemberValue(string? enumMemberValue, StringComparison comparisonType)
        {
            return TryParseFromEnumMemberValue(enumMemberValue, comparisonType, out Colors result) ? result : null;
        }
 
        /// <summary>
        /// Converts the string representation of the value associated with one enumerated constant to
        /// an equivalent enumerated object.
        /// </summary>
        /// <param name="enumMemberValue">The value as defined with <see cref="System.Runtime.Serialization.EnumMemberAttribute"/>.</param>
        /// <returns>
        /// Contains an object of type Colors whose value is represented by value if the parse operation succeeds.
        /// If the parse operation fails, result contains a null value.
        /// </returns>
        public static Colors? TryParseFromEnumMemberValue(string? enumMemberValue)
        {
            return TryParseFromEnumMemberValue(enumMemberValue, StringComparison.Ordinal, out Colors result) ? result : null;
        }
 
        /// <summary>Retrieves an array of the values of the constants in the Colors enumeration.</summary>
        /// <returns>An array that contains the values of the constants in Colors.</returns>
        public static Colors[] GetValues()
        {
            return new[]
            {
                Colors.None,
                Colors.Red,
                Colors.Green,
                Colors.Blue,
            };
        }
 
        /// <summary>Retrieves an array of the names of the constants in Colors enumeration.</summary>
        /// <returns>A string array of the names of the constants in Colors.</returns>
        public static string[] GetNames()
        {
            return new[]
            {
                nameof(Colors.None),
                nameof(Colors.Red),
                nameof(Colors.Green),
                nameof(Colors.Blue),
            };
        }
 
        private static bool TryParseNumeric(
            string name,
            StringComparison comparisonType,
            out int result)
        {
            switch (comparisonType)
            {
                case StringComparison.CurrentCulture:
                case StringComparison.CurrentCultureIgnoreCase:
                    return int.TryParse(name, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
                case StringComparison.InvariantCulture:
                case StringComparison.InvariantCultureIgnoreCase:
                case StringComparison.Ordinal:
                case StringComparison.OrdinalIgnoreCase:
                    return int.TryParse(name, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out result);
                default:
                    return int.TryParse(name, out result);
            }
        }
    }
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// <auto-generated />
#nullable enable
 
using System;
using System.Diagnostics.CodeAnalysis;
 
#pragma warning disable CS1591 // publicly visible type or member must be documented
 
namespace EnumClassDemo
{
    [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Raiqub.Generators.EnumUtilities", "1.6.0.0")]
    public static partial class ColorsValidation
    {
        /// <summary>Returns a boolean telling whether the value of <see cref="Colors"/> instance exists in the enumeration.</summary>
        /// <returns><c>true</c> if the value of <see cref="Colors"/> instance exists in the enumeration; <c>false</c> otherwise.</returns>
        public static bool IsDefined(Colors value)
        {
            return value switch
            {
                Colors.None => true,
                Colors.Red => true,
                Colors.Green => true,
                Colors.Blue => true,
                _ => false
            };
        }
 
        public static bool IsDefined(
            [NotNullWhen(true)] string? name,
            StringComparison comparisonType)
        {
            return name switch
            {
                { } s when s.Equals(nameof(Colors.None), comparisonType) => true,
                { } s when s.Equals(nameof(Colors.Red), comparisonType) => true,
                { } s when s.Equals(nameof(Colors.Green), comparisonType) => true,
                { } s when s.Equals(nameof(Colors.Blue), comparisonType) => true,
                _ => false
            };
        }
 
        public static bool IsDefinedIgnoreCase([NotNullWhen(true)] string? name)
        {
            return IsDefined(name, StringComparison.OrdinalIgnoreCase);
        }
 
        public static bool IsDefined([NotNullWhen(true)] string? name)
        {
            return name switch
            {
                nameof(Colors.None) => true,
                nameof(Colors.Red) => true,
                nameof(Colors.Green) => true,
                nameof(Colors.Blue) => true,
                _ => false
            };
        }
    }
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/EnumUtilities

RSCG – CommonCodeGenerator

name CommonCodeGenerator
nuget https://www.nuget.org/packages/CommonCodeGenerator/
link https://github.com/usausa/common-code-generator
author yamaokunousausa

Generating ToString from classes

 

This is how you can use CommonCodeGenerator .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="CommonCodeGenerator" Version="0.2.0" />
        <PackageReference Include="CommonCodeGenerator.SourceGenerator" Version="0.2.0">
            <PrivateAssets>all</PrivateAssets>
            <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
    </ItemGroup>
 
    <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
</Project>

The code that you will use is

1
2
3
4
5
6
7
using ToStringData;
 
Console.WriteLine("Hello, World!");
Person person = new ();
person.FirstName = "Andrei";
person.LastName = "Ignat";
Console.WriteLine(person.ToString());
01
02
03
04
05
06
07
08
09
10
11
12
using CommonCodeGenerator;
 
namespace ToStringData;
[GenerateToString]
internal partial class Person
{
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
 
    [IgnoreToString]
    public int Age { get; set; }
}

 

The code that is generated is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
// <auto-generated />
#nullable disable
namespace ToStringData
{
    partial class Person
    {
        public override string ToString()
        {
            var handler = new global::System.Runtime.CompilerServices.DefaultInterpolatedStringHandler(0, 0, default, stackalloc char[256]);
            handler.AppendLiteral("Person ");
            handler.AppendLiteral("{ ");
            handler.AppendLiteral("FirstName = ");
            handler.AppendFormatted(FirstName);
            handler.AppendLiteral(", ");
            handler.AppendLiteral("LastName = ");
            handler.AppendFormatted(LastName);
            handler.AppendLiteral(" }");
            return handler.ToStringAndClear();
        }
    }
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/CommonCodeGenerator

Pattern: FluentInterface

Description

Fluent interface allows you do have method chaining

Example in .NET :

FluentInterface

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using Microsoft.Extensions.DependencyInjection;
using System.Data;
using System.Data.Common;
 
namespace FluentInterface;
internal static class FluentInterfaceDemo
{
    public static ServiceCollection AddServices(this ServiceCollection sc)
    {
        //just for demo, does not make sense
        sc
            .AddSingleton<IComparable>((sp) =>
            {
                //does not matter
                return 1970;
            })
            .AddSingleton<IComparable<Int32>>((sp) =>
            {
                //does not matter
                return 16;
            });
        //this way you can chain the calls , making a fluent interface
        return sc;
 
 
    }
}

Learn More

Source Code for Microsoft implementation of FluentInterface

SourceCode Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton

Learn More

Wikipedia

}

Homework

Implement a class person that you can see the first name and last name as fluent interface

Pattern: Chain

Description

Chain of responsibility pattern allows an object to send a command without knowing what object will receive and handle it. Chain the receiving objects and pass the request along the chain until an object handles it

Example in .NET :

Chain

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
namespace Chain;
 
public static class ChainDemo
{
    public static int SecondException()
    {
        try
        {
            FirstException();
            return 5;
        }
        catch (Exception ex)
        {
            throw new Exception($"from {nameof(SecondException)}", ex);
        }
    }
    static int FirstException()
    {
        throw new ArgumentException("argument");
    }
}

Learn More

Wikipedia

Homework

Implement a middleware in ASP.NET Core that intercepts the exception and logs it to the database. The middleware should be able to pass the exception to the next middleware in the chain.

Pattern: Decorator

Description

Decorator allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.

Example in .NET :

Decorator

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
namespace Decorator;
internal class DecoratorDemo
{
    public static void Stream_Crypto_Gzip()
    {
        string nameFile = "test.txt";
        if (File.Exists(nameFile))
            File.Delete(nameFile);
        byte[] data = ASCIIEncoding.ASCII.GetBytes("Hello World!");
        //first time we have a stream
        using (var stream = new FileStream(nameFile, FileMode.OpenOrCreate, FileAccess.Write))
        {
            //stream.Write(data, 0, data.Length);
            //return;
             
            var cryptic = new DESCryptoServiceProvider();
 
            cryptic.Key = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
            cryptic.IV = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
            //we decorate the initial stream with a crypto stream
            using (var crStream = new CryptoStream(stream, cryptic.CreateEncryptor(), CryptoStreamMode.Write))
            {
                //and we decorate further by encoding
                using (var gz = new GZipStream(crStream, CompressionLevel.Optimal))
                {
                    gz.Write(data, 0, data.Length);
                }
 
            }
        }
    }
}

Learn More

Wikipedia

Homework

1. Add a logging to DBConnection . 2. Use by decorating a coffee with milk, sugar, and chocolate (and maybe other condiments). The coffee should be able to display the condiments in a Display method and calculate the price of the coffee with milk, sugar, and chocolate.

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.