✅ 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:
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
33 Replies
why not have the user pass in a collection of arguments?
you mean asking the user for the arguments?
or create a strongly typed object with all the possible arguments for each endpoint
depends on the api if thats a good idea or not
yeah
what youre doing now seems too convoluted for no apparent benefit to me
its wrapping a weather api, so the idea is that there are methods like GetPastWeather() or GetCurrentWeather() and the user passes (for example) the coordinates of the location, so i'm not sure how i would implement that
method overloads
one for coordinates, one for location name, etc
ok i get you
that was my initial idea
or simply
GetAsync<T>(string service, IDictionary<string, object> values)
, or string,string if you want to format the values in Example1/Example2that's what i was doing, but in every example method i needed to create a new dictionary, while hardcoding the names of the parameters
there's not really a problem with that
all you need is
IEnumerable<KeyValuePair<TKey,TValue>>
but i was trying to repeat less code
you can create an overload that takes a span to avoid allocs
if youre on .net 9 you can use
params
with thati'm on .net 8
repeating less isnt always better
i'd also change the query string creation to escape the keys/values properly
people follow DRY too religiously
how would i do that?
and in a lot of cases end up with way less readable or overengineered code
url encode
ok i'll be doing that next
although iirc HttpClient should handle that but dont quote me
i don't know if this image is readable but this is the code i'm using to send the request
just to clear anything up
so in this case getparameters() is kind of overkill?
think it should be
$"{Uri.EscapeDataString(x.Key)}={Uri.EscapeDataString(x.Value)}"
use
GetFromJsonAsync
but method overloads seem like the best option here
definitely
thats not what reflection is intended forok thanks for the help
i'll use that thanks
do i need to escape the key if i'm going to be hardcoding them?
no, then you know what they are
hardcode the url encoded version
alright thanks again for the help
np
btw if i configured my httpclient with a baseurl that will still work with GetFromJsonAsync right
just making sure
yeah
nice
do i delete the post now?
$close
If you have no further questions, please use /close to mark the forum thread as answered