making an object's or method's properties variable

  • Thread starter Thread starter Lance
  • Start date Start date
L

Lance

Hi,

Is there a way to call an object or method, but use a variable to represent
the method or property to be used? eg:

I want to create a regular expression, but the regexp options I want to wait
until runtime to decide which options to use.

The following attempt throws an error:

string rxo = "MultiLine";
Regex rx = new Regex( sRegex, RegexOptions.rxo);

Thanks,
Lance
 
Hi Lance,

In general what you want is not easy to do, interpretate a string as code
is possible using reflection but is still a very difficult subject.

in particular you case is not very difficult, as the string you are trying
to be interpreted is part of a enumeration.

You have two options for this case:
1- Use a switch statement:
switch (rxo)
{
case"MultiLine" :
}

2- You can use Enum.Parse :

RegexOptions op = (RegexOptions) Enum.Parse( typeof(RegexOptions),
"MultiLine");


In your particular example I will go for the second one.

Cheers,
 
Thanks, the second one worked a treat!

Ignacio Machin ( .NET/ C# MVP ) said:
Hi Lance,

In general what you want is not easy to do, interpretate a string as code
is possible using reflection but is still a very difficult subject.

in particular you case is not very difficult, as the string you are trying
to be interpreted is part of a enumeration.

You have two options for this case:
1- Use a switch statement:
switch (rxo)
{
case"MultiLine" :
}

2- You can use Enum.Parse :

RegexOptions op = (RegexOptions) Enum.Parse( typeof(RegexOptions),
"MultiLine");


In your particular example I will go for the second one.

Cheers,
 
Back
Top