RSCG – PropertyResolvers

RSCG – PropertyResolvers
 
 

name PropertyResolvers
nuget https://www.nuget.org/packages/PropertyResolvers/
link https://github.com/tombiddulph/PropertyResolvers
author Tom Biddulph

Generating code for switch for property in C#

 

This is how you can use PropertyResolvers .

The code that you start with is


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="PropertyResolvers" Version="0.0.9">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="PropertyResolvers.Attributes" Version="0.0.9" />
  </ItemGroup>
	<PropertyGroup>
		<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
		<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
	</PropertyGroup>

</Project>


The code that you will use is


using PropertyResolvers.Attributes;
[assembly: GeneratePropertyResolver("Name",IncludeNamespaces = ["PropSwitch"])]

namespace PropSwitch;

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
}

public class College
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
}




using PropSwitch;

Person p=new() { Id = 1, Name = "Andrei" };
College c = new() { Id = 1, Name = "Mathematics" };
Console.WriteLine(NameResolver.GetName(p));
Console.WriteLine(NameResolver.GetName(c));

 

The code that is generated is

// <auto-generated/>
#nullable enable

namespace PropSwitch;

public static class NameResolver
{
    public static string? GetName(object? obj) => obj switch
    {
        global::PropSwitch.Person x => x.Name.ToString(),
        global::PropSwitch.College x => x.Name.ToString(),
        _ => null
    };

}

// <auto-generated/>
#nullable enable

using System.Runtime.CompilerServices;

namespace PropSwitch;

[CompilerGenerated]
internal static class PropertyResolverModuleInitializer
{
    [ModuleInitializer]
    internal static void Initialize()
    {
            global::PropertyResolvers.Attributes.PropertyResolverRegistry.Register("Name", global::PropSwitch.NameResolver.GetName);
    }
}

Code and pdf at

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


Posted

in

,

by

Tags: