dotnet / dotnet/command-line-api

Double generic types and members with non-generic equivalents

Open
#2,757 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
3.7k
Forks
428
PR merge metrics
No merged PRs in 30d

Description

## Examples

```csharp
// In addition to these:
T? ParseResult.GetValue(Option option);
new Option(string name, params string[] aliases);
// etc...

// Make it possible to call them like this:
object? ParseResult.GetValue(Option option, Type valueType);
new Option(Type valueType, string name, params string[] aliases);
```

This is somewhat similar to what we have in DI:

```csharp
// We can add service like this:
services.AddSignleton();

// Or this:
services.AddSingleton(Type serviceType);
```

## Justification
I am making my own library that adds proper hosting API, making using `System.CommandLine` similar to any regular ASP.NET project.
For example:

`Program.cs`
```csharp
app.MapCommand("foo", ([Option] FileInfo file) =>
{
foreach (string line in File.ReadLines(file.FullName))
Console.WriteLine(line);
});
```

`ShellApplication.cs`
```csharp
public void MapCommand(string name, Delegate command)
{
RootCommand rootCommand = [];
ParameterInfo[] parameters = command.Method.GetParameters();

foreach (ParameterInfo parameterInfo in parameters)
{
if (parameterInfo.GetCustomAttribute() is not null)
{
Option option = (typeof(Option<>).MakeGenericType(parameterInfo.ParameterType).GetConstructor([typeof(string), typeof(string[])])!.Invoke([name]) as Option)!;
rootCommand.Options.Add(option);
}
}
// etc...
}
```

At first glance this looks fine – just make a generic type using reflection. Only the problem is that this is not AOT compatible and [will cause exceptions](https://github.com/dotnet/runtime/issues/71625). Adding alternatives that accept types as parameters would solve this.

## Additional context

I've glossed over the codebase, and it doesn't look like it will be that hard to implement changes. If that's ok with you, I can prepare a PR myself.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.