❔ Getting property from object based on input
Is it possible to create a function that would look something like this? Here I already have the object and I know for sure that the property actually exists. I'm quite new to C#, so I don't know if this is actually possible
13 Replies
yes, but why do you want this?
You're likely just looking for a dictionary
The object is pulled from a database and I need to sometimes update things of it
I don't want to make a function for every seperate part
Right now I have like 4 different functions to update a single property, for example:
What does
myObject
look likeSome different values, so something like this:
There are no other objects in there
Firstly, properties, methods and types in C# should be PascalCase
Oh yea, they are, I just made a wrong example
There's quite a lot of them so I didn't copy paste all of them
fair
There that is better
So if I'm understanding correctly, you're receiving a string from the database and you want to set all these properties to their corresponding values?
Well upon pressing a button, I want to change a value
And I want to be able to pass the property that I want to change as well as the new value
I have like 10 buttons that all change different values and instead of creating 10 different functions, I was wondering if it possible to combine that into one function
So function should look something like this:
And then
T
is the type, because I have different types of properties within my objectYou can do this using reflection, but that's 1) very slow, and 2) not type-safe
You'd have to pass
object
to ChangeProperty
method instead of a specific typeHmm okay, thanks. Would it be faster if I make a seperate method per type of value?
So like
changePropertyString(string property, string value)
changePropertyInt(string property, int value
Etc.Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.