0

This question was a very tough one to find the right words for, so please don't blame me too much :).

Basically here is the situation:

1) I KNOW how to get the name of a variable;

2) I KNOW how to access a variable via reflection, knowing it's name.

What I want is to get the name (string) dynamicaly and immediately receive access to a non-static variable using the string I've just derrived WITHOUT making an empty class instance for that.

Confusing right? Well, here is the deal: we have a winforms project, when the project was started, we decided that we will not inherit our forms from our very own parent, that is all of our forms inherit the basic Microsoft's Form. Right now we have a situation, where we have some of the forms with a common functionality (say search) and some without. What we want is to be able to call the common methods on the currently active from from the other form IF THEY EXIST.

Simple to do, right?

Form currentlyActiveForm = GetCurrentlyActiveForm();  // imagine we have this method

dynamic currentForm = currentlyActiveForm;
try
{
currentForm.CommonMethod();
}
catch
{
}

Ugly? Maybe, but that is how it is in our project right now and it gets the job done. My problem with this? If I press Shift+F12 on any of the CommonMethod() definitions I see no references at all. Am I being picky? Maybe, but still I want to know the following code is possible in the All Mighty language:

Form currentlyActiveForm = GetCurrentlyActiveForm();
string commonMethodName = MyUtils.GetVariableName(() => MyChildForm.CommonMethod);
// mind, CommonMethod() is NON-static!
...
[proceed to access and call the method, using reflection]

So is the above code possible without getting a compiler error?

Community
  • 1
  • 1
cubrman
  • 884
  • 1
  • 9
  • 22
  • You are using the word 'variable' ambiguously. Do you really mean variable, field or property? Also in the lower half of your text you suddenly talk about invoking a method and not a 'variable' anymore. Can you please clarify that by updating you question? – thehennyy Aug 16 '16 at 12:59
  • Also, using reflection will NOT change the visual studio behavior of not showing the references, because for the static analyser they do not exist. – thehennyy Aug 16 '16 at 13:03
  • Well, I meant an operation of accessing a non-static functionality of a class, sorry for the confusion. Tbh, I've just realized that my idea is a false one because different methods/variables across different children of the same parent never have anything in common even when they have the same name. The solution here should be in the code architecture not in the naming and reflection. I am thinking about deleting my question right now. – cubrman Aug 16 '16 at 13:24

0 Answers0