C#C
C#3y ago
InsertPi

✅ Use Roslyn to auto-generate overloads of method

I'm working on some code and the amount of overloads I'm having to write is very quickly getting out of hand. I have a bunch of related functions which are overloaded based on the number of parameters in a provided Action. For example, one of the longer methods looks like:

        internal void DispatchKernel<T, U, V, W, X, Y, Z, A>(int start, int end, Buffer<T> buf1, Buffer<U> buf2, Buffer<V> buf3, Buffer<W> buf4, Buffer<X> buf5, Buffer<Y> buf6, Buffer<Z> buf7, Buffer<A> buf8, Action<Index, GPUArray<T>, GPUArray<U>, GPUArray<V>, GPUArray<W>, GPUArray<X>, GPUArray<Y>, GPUArray<Z>, GPUArray<A>> action, string src)
            where T : unmanaged
            where U : unmanaged
            where V : unmanaged
            where W : unmanaged
            where X : unmanaged
            where Y : unmanaged
            where Z : unmanaged
            where A : unmanaged
        {
            var idx = new Index(start);

            var kernel = GetKernel(action, src);

            kernel(((end - start) / block_size, block_size), idx,
                new GPUArray<T>(buf1),
                new GPUArray<U>(buf2),
                new GPUArray<V>(buf3),
                new GPUArray<W>(buf4),
                new GPUArray<X>(buf5),
                new GPUArray<Y>(buf6),
                new GPUArray<Z>(buf7),
                new GPUArray<A>(buf8));

            Synchronize();
        }


I came across a blog post here about source generators in .NET 7, and was curious if I could use similar techniques here to totally omit the need to hand-write all these overloads and leave it to a source generator. However, I've never used anything related to source generators or Roslyn before and would like some guidance. Any help would be appreciated.

(Tagging both intermediate and advanced since I'm not sure what this is considered-- someone let me know)
Exploring .NET source generators to reduce boilerplate code in everyday code!
Was this page helpful?