Advertisement

Can you append or prefex Members or Variable names with variables in C#?

Started by December 11, 2018 11:50 PM
3 comments, last by Shaarigan 5 years, 11 months ago

Is it possible to use variables strings to change member calls in your code?

For example... say you have a few members in your class called
 


RunSomthing_Start()
RunSomthing_Process()
RunSomthing_End() 

is there a way to call them with somthing like this in code elsewhere in your project?


action = "_Start";
classObject.RunSomething+action();

action = "_Process";
classObject.RunSomething+action();

action = "_End";
classObject.RunSomething+action();

I know you can use parameters.. like


action = "_Start";
classObject.RunSomething(action);

action = "_Process";
classObject.RunSomething(action);

action = "_End";
classObject.RunSomething(action);

This is more just a curiosity question... like can you use string functions like you have in Console.Write(); to append stuff onto the name of Functions and Variables?


int object_+getObjectID() = someValue.

So the actual variable has a unique name based on the object.. not just the value in the variable.

: GameDev.Net Blog: Open Blog; Read Blog : My uTube Chans : TragicTableTopTragicDeskTop

I don't think so...  That being said, I'm not really well versed on anything but day-to-day practical c#.. so, maybe I'm wrong.?

In order for this to work it would have to be a HUGE feature of the compiler.  The only circumstance that I know of where object names are altered is in the compile stage when Obfuscation is used to hide the names/purposes of the code to make de-compilation harder..

Advertisement

Sure you can. The key word here is Reflection. You can inspect all your classes, members, etc. You're looking for invoking a method.

Lookie here:

https://docs.microsoft.com/en-us/dotnet/api/system.type.invokemember?view=netframework-4.7.2

 

Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>

You can somehow using reflection as mentioned above but I don't recommend to do that because runtime performance would be terrible. You can also put all of those functions into a Dictionary<string, Delegate> and use that to maybe do things like


RunSomething["action"]();

but again, runtime performance would be terrible.

The closest you can come to is using another class to wrap your functions into so you end up with


MyClass.RunSomething.Action();

Anything else is reserved for runtime resolved scripting languages

This topic is closed to new replies.

Advertisement