C
C#2y ago
QuickZ

❔ Is there a way to access a prop with the help of a string.

Is there a way to access a prop with the help of a string. Like you do in JS like this myObject["propName"]; ?
9 Replies
QuickZ
QuickZOP2y ago
a external app is returning props with first nested level being the ids as propnames. I have the ids in string already available. I want to be able to automatically access them. dto be looking like this for example
public class ReturnedDtoFromAPI
{
public SomeClass c7855x231323acs39a5 { get; set; }
public string ErrorMessage { get; set; }
}
public class ReturnedDtoFromAPI
{
public SomeClass c7855x231323acs39a5 { get; set; }
public string ErrorMessage { get; set; }
}
And I want to just map away from the Id so my frontend dont need to know about it but still automatically access by iterating through several of these objects. Which will be possible if I just map the level with id away. Which I will be able to if I just can access it like the question asks for So if it was js syntax I would just access it like
var dtoToRetunToFrontend = returnedDtoFromApi[idString];
var dtoToRetunToFrontend = returnedDtoFromApi[idString];
want to do achieve same result in c# now
Thinker
Thinker2y ago
If you have the class structure then why do you want to access properties dynamically?
QuickZ
QuickZOP2y ago
because I dont want the same structure in the frontend Reasons: I dont want frontend to see the ids, and I dont want to manually change dtos as soon as I add something to the array, or remove.
Thinker
Thinker2y ago
I'm too tired to think about whether that's a good idea. Anyway, you can use reflection and do yourObject.GetType().GetProperty("PropName").GetValue(yourObject).
QuickZ
QuickZOP2y ago
The bad idea is that the API is returning the dtos like this. But its out of my reach to change it since its 3rd party 🙂 ooh GetValue... forgot that last step been trying GetProperty()
Thinker
Thinker2y ago
GetProperty just returns an object representing the property itself, not bound to any object.
QuickZ
QuickZOP2y ago
was not getting the intellisense for that one ah never mind this API is making me f'd anyway due to response.Content.ReadAsAsync<DtoNeededHereAsWell>() Unless I try to be cleaver with the json while its serialized as string. 🤢 So still have to edit Dto as soon as expected ids change
QuickZ
QuickZOP2y ago
Ye I guess Newtonsofts JObjects is the way to go. and later serialize it. Or automap. not sure what I get yet https://stackoverflow.com/questions/16459155/how-to-access-json-object-in-c-sharp
Stack Overflow
how to access JSON object in C#
I receive the following Json through a web service: { report: { Id: "aaakkj98898983" } } I want to get value of the Id. How to do this in C#? THANKS
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server