NTypewriter icon indicating copy to clipboard operation
NTypewriter copied to clipboard

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

Open blahDL opened this issue 6 months ago • 0 comments

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"))

blahDL avatar Aug 05 '24 07:08 blahDL