Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access objects within new {int a, string b}

I have a method

public Action FirstAction(object data)
{
}

I have to pass two variables to this class which are different types for example int and string or any other type of objects.

I read that I can do it by

FirstAction( new{int a, string b} )

My question is how to access the two separated variables within FirstAction method?

Note: I cannot change the object parameters to object[] or params object[]; it needs to be done with the current signature.

like image 550
Martin Nikolaev Avatar asked Dec 03 '22 15:12

Martin Nikolaev


1 Answers

If you cannot change the function signature, then you can always use dynamic:

public Action FirstAction(object data) { 
     dynamic dataAsDynamic = data;
     int a = dataAsDynamic.a;
     string b = dataAsDynamic.b;
}

Note that this is very brittle as the minute someone changes the names of these fields the code will break. I don't actually recommend doing this, but if you have no control over the function signature then you're kinda stuck.

like image 152
Asik Avatar answered Dec 28 '22 03:12

Asik