Leroico
Leroico
CC#
Created by Leroico on 1/4/2025 in #help
✅ Getting method parameters with reflection on library code
Hi everyone, so I'm making a wrapper/library for a rest api, and to trying to simplify the code i ended up using reflection to get a method's parameters, something like this:
async Task<T> GetAsync(string service, ParameterInfo[] parameters, params object[] values)
{
// make dictionary from parameters and values
Dictionary<string, string> args = ...

// make the http request and return the response
HttpRequestMessage request = new(HttpMethod.Get, $"{service}?{string.Join('&', args.Select(x => $"{x.Key}={x.Value}"))}");
...
}

// here's where i'm using reflection
async Task<Model1> Example1(int arg1, int arg2, string arg3) =>
await GetAsync<Model1>("service1", MethodBase.GetCurrentMethod().GetParameters(), arg1, arg2, arg3);

async Task<Model2> Example2(double arg1, char arg2) =>
await GetAsync<Model2>("service2", MethodBase.GetCurrentMethod().GetParameters(), arg1, arg2);
async Task<T> GetAsync(string service, ParameterInfo[] parameters, params object[] values)
{
// make dictionary from parameters and values
Dictionary<string, string> args = ...

// make the http request and return the response
HttpRequestMessage request = new(HttpMethod.Get, $"{service}?{string.Join('&', args.Select(x => $"{x.Key}={x.Value}"))}");
...
}

// here's where i'm using reflection
async Task<Model1> Example1(int arg1, int arg2, string arg3) =>
await GetAsync<Model1>("service1", MethodBase.GetCurrentMethod().GetParameters(), arg1, arg2, arg3);

async Task<Model2> Example2(double arg1, char arg2) =>
await GetAsync<Model2>("service2", MethodBase.GetCurrentMethod().GetParameters(), arg1, arg2);
Now i've heard that reflection is pretty inefficient, so considering that this is library code that other people might end up using, is this a bad idea? should i try another, maybe more efficient, method? btw i have no idea what tags i should add to this
50 replies