NeVeSpl / NTypewriter

File/code generator using Scriban text templates populated with C# code metadata from Roslyn API.
https://nevespl.github.io/NTypewriter/
MIT License
126 stars 24 forks source link

Suggestion: Use generic types for functions provided in SymbolsFunctions (and others) #122

Open blahDL opened 3 months ago

blahDL commented 3 months ago

When making use of the functions provided by classes such as SymbolsFunctions in C# code we have to cast the type back to the original type to access additional properties on the objects.

// to get the list of all parameters that have the `FromRoute` attribute across all controllers you have to do something like this
 classes
    .ThatInheritFrom("ControllerBase")
    .Cast<IClass>() // ThatInheritFrom returns a collection of ISymbolBase so we need to cast it back to IClass
    .SelectMany(controller => controller.Methods)
    .SelectMany(method => method.Parameters.ThatHaveAttribute("FromRoute"))
    .Cast<IParameter>() // ThatHaveAttribute returns a collection of ISymbolBase so we need to cast it back to IParameter

This should be relatively simple and low risk to implement. For example the following function WhereNamespaceStartsWith

public static IEnumerable<ISymbolBase> WhereNamespaceStartsWith(this IEnumerable<ISymbolBase> symbols, string prefix)
{
    var result = symbols.Where(x => x.Namespace.StartsWith(prefix));
    return result;
}

Could be updated as follows

public static IEnumerable<T> WhereNamespaceStartsWith<T>(this IEnumerable<T> symbols, string prefix) where T: ISymbolBase
{
    var result = symbols.Where(x => x.Namespace.StartsWith(prefix));
    return result;
}

If this was updated for all functions provided the example at the start of this issue would no longer need to cast the type back to the original type so it would be as follows

// to get the list of all parameters that have the `FromRoute` attribute across all controllers you can do this
 classes
    .ThatInheritFrom("ControllerBase")
    .SelectMany(controller => controller.Methods)
    .SelectMany(method => method.Parameters.ThatHaveAttribute("FromRoute"))