Giter Club home page Giter Club logo

learn.sourcegenerator's Introduction

Learn Source Generator in .NET

Overview

Ever wanted to type less for the most common things you type over and over? Oh yes, me too. Probably would shave off 6-months lost time over the years.

Geting started

Basic Generator

  1. Create 2 projects:
    • Console App: Sample.ConsoleApp
    • Standard Library: Learn.SourceGenerator
  2. Add NuGet packages to the Standard Lib project, Microsoft.CodeAnalysis.Analyzers and Microsoft.CodeAnalysis.CSharp.

Console App

  1. In the console app, change the class type from internal class to partial class.
  2. Next, add our method we're going to generate
namespace Sample.ConsoleApp;

// Refactor fron `internal class` to `partial class`
partial class Program
{
  static partial void HelloFrom(string name);

  static void Main(string[] args)
  {
    HelloFrom("my generated method Code");
  }
}
  1. Reference the source generator library
  2. Modify the Console App's csproj file
<!-- Add this as a new ItemGroup, replacing paths and names appropriately -->
<ItemGroup>
    <ProjectReference Include="..\PathTo\SourceGenerator.csproj"
                      OutputItemType="Analyzer"
                      ReferenceOutputAssembly="false" />
</ItemGroup>

Generator - Standard Library

using Microsoft.CodeAnalysis;

namespace Learn.SourceGenerator
{
  [Generator]
  public class HelloGenerator : ISourceGenerator
  {
    public void Execute(GeneratorExecutionContext context)
    {
      // Code generation goes here

      // Find the main method
      var mainMethod = context.Compilation.GetEntryPoint(context.CancellationToken);

      // Build up the source code
      string source = $@" // Auto-generated code
using System;

namespace {mainMethod.ContainingNamespace.ToDisplayString()}
{{
  public static partial class {mainMethod.ContainingType.Name}
  {{
    static partial void HelloFrom(string name) =>
      Console.WriteLine($""Generator says: Hi from '{{name}}'"");
  }}
}}
";
      var typeName = mainMethod.ContainingType.Name;

      // Add the source code to the compilation
      context.AddSource($"{typeName}.g.cs", source);
    }

    public void Initialize(GeneratorInitializationContext context)
    {
      // No initialization required for this one
    }
  }
}

References

learn.sourcegenerator's People

Contributors

damiansuess avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.