© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
6 replies
Ploxi

Best Practices for Instantiating Objects in C# Source Generators

I am writing a sourcegen.
We need a way of instantiating SomeArgs in SomeService.
Currently the sourcegen is just newing up SomeArgs.

[CreateConfigurableTask]
public class SomeArgs
{
    public string SomeStuff { get; set; }
    public string SomeStuff1 { get; set; }

    public SomeArgs WithSomeStuff(string someStuff)
    {
        SomeStuff = someStuff;
        return this;
    }

    public async Task<SomeArgs> SomeAsyncOperation(string myParam)
    {
        await Task.Delay(10);
        return this;
    }
}

public partial class SomeService
{
    private Task<string> DoSomething(SomeArgs data)
    {
        return Task.FromResult($"Doing something with {data.SomeStuff} and {data.SomeStuff1}");
    }
}
[CreateConfigurableTask]
public class SomeArgs
{
    public string SomeStuff { get; set; }
    public string SomeStuff1 { get; set; }

    public SomeArgs WithSomeStuff(string someStuff)
    {
        SomeStuff = someStuff;
        return this;
    }

    public async Task<SomeArgs> SomeAsyncOperation(string myParam)
    {
        await Task.Delay(10);
        return this;
    }
}

public partial class SomeService
{
    private Task<string> DoSomething(SomeArgs data)
    {
        return Task.FromResult($"Doing something with {data.SomeStuff} and {data.SomeStuff1}");
    }
}


Here are some ideas:
- Mark a method with an attribute that generates SomeArgs like that:
[ConfigurableTaskArgsFactory]
public SomeArgs CreateSomeArgs()
{
    return new SomeArgs();
}
[ConfigurableTaskArgsFactory]
public SomeArgs CreateSomeArgs()
{
    return new SomeArgs();
}

- The sourcegen simply using IServiceProvider to get the instance of SomeArgs behind the scenes. Could be hard to see through what is happening.
- Use a delegate in the generated partial class to create SomeArgs like that:
public partial class SomeService
{
    private Func<SomeArgs> _createSomeArgs = () => new SomeArgs();
}
public partial class SomeService
{
    private Func<SomeArgs> _createSomeArgs = () => new SomeArgs();
}


What are your thoughts on this?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ C# best practices clarification
C#CC# / help
3y ago
❔ best practices for updating objects using GroupBy
C#CC# / help
3y ago
Source generators VSCode
C#CC# / help
2y ago
Source Generators In Nuget Packages
C#CC# / help
3y ago