Re: Reflection and variable selection? Late binding?



Hi Ben,

No reflection or binding needed:

string text = null;

switch (variableName)
{
case "foo":
text = foo.ToString();
break;
case "bar":
text = bar.ToString();
break;
}

MessageBox.Show(text);


I'm not sure it's such a good idea to pass in the name of a local variable though. An Enum would be appropriate here instead:

enum DoSomethingChoice
{
Foo,
Bar
}

class FooBarChoiceTest
{
int foo = 1, bar = 2;

void DoSomething(DoSomethingChoice choice)
{
string text = null;

switch (choice)
{
case DoSomethingChoice.Foo:
text = foo.ToString();
break;
case DoSomethingChoice.Bar:
text = bar.ToString();
break;
default:
throw new System.ComponentModel.InvalidEnumArgumentException(
"choice", (int) choice, typeof(DoSomethingChoice));
}

MessageBox.Show(text);
}
}

--
Dave Sexton

"Ben R." <benr@xxxxxxxxxxxxxxxx> wrote in message news:AF6EED6C-7C1C-4C7B-93D2-2A01231C7552@xxxxxxxxxxxxxxxx
Hi,

I learned that for my.sttings, I can pull an entry by name, but can I use
reflection to load a varaible? Example

void dosomething(string variablename)
// note: value passed in for variable name is "foo"
int foo=1
int bar=2

messagebox.show(reflectionhere(variablename));

I want 1 to show up.

Is this possible? Is this what late binding is? There are circumstances
where it'd be nice to construct a string which will represent a varaible name
that I'd like to use.

Thank you...

-Ben





.



Relevant Pages

  • Re: cast ?
    ... That's exactly (switch) what I wanted to avoid keeping in mind that we can ... string into the object internal format. ... Reflection is slower than compiled code. ... didn't you say that you're reading this out of a database? ...
    (microsoft.public.dotnet.csharp.general)
  • Re: cast ?
    ... That's exactly (switch) what I wanted to avoid keeping in mind that we can ... create any object of any type on run-time using Reflection and the type name ... string into the object internal format. ... compiler optimization, and then use Reflection in your default case. ...
    (microsoft.public.dotnet.csharp.general)
  • Re: Change Text to Memo
    ... Switch a given table field to Memo ... Function SwitchFieldType(sDb As String, sTableName As String, sFieldName ... Dim sSQL As String ... If Err.Number = 0 Then Exit Function ...
    (microsoft.public.access.modulesdaovba)
  • Re: proposal: reswitch
    ... > which levels of loops and/or switches and/or ... socket -server command ?-myaddr addr? ... You've got the quick-exit (break, no string), the fall-through to next ... -switch option), then it'd be the nth switch. ...
    (comp.lang.tcl)
  • Re: Initialize constants
    ... The Variable class has a public String method that returns the full ... public String getVariable(String variableName) throws Exception; ... Now to initialize Constants.FILE_NAME, I need to call getPathto ...
    (comp.lang.java.programmer)