vendredi 9 août 2019

c# Creating a reusable method to access properties inside object

Apologies as I know the title sounds ambiguous but i couldn't word it any better

So, i will try to keep it very simple and short. Let's say i have a User object with an int property caled UserID and i'm accessing it as follows :

var value = instanceofUser.UserID;

Is there way i can create a reusable method that can access a given property of a given object ? This is what i'm trying to achieve :

void GetTheValue(object parent, property nameOfProperty)
{
  var value = parent.nameOfProperty;
}

The reason behind this is that i have a similar case, and i have to rewrite the entire code block(not this exact one, but kinnda the same) over and over again. So, what would be the approach here to make something re-usable so that i can access any given property of any given object ?

I am thinking of going with Reflection or generics however, right now, i don't have the slightest idea of what to either search or implement. Any suggestions would be helpful!





Aucun commentaire:

Enregistrer un commentaire