1

C# code I want to execute :

FullReservationDataControl1.SetData(Reservation);

but instead of typing 'FullReservationDataControl1' I want to loop it, so I made a for loop to get me an array of strings having this content : FullReservationDataControl+xwhere x is a number. so my question is how to use a string to execute a command and not ending with an error due to execution of :

"FullReservationDataControl4".SetData(Reservation);
Skyliquid
  • 374
  • 1
  • 5
  • 23
  • 2
    You want an array of controls. – SLaks Oct 26 '14 at 18:15
  • I think you will need to structure your classes and code for a better approach to handle this issue, but here is a similar issue: http://stackoverflow.com/questions/13720565/is-there-anything-like-javascript-eval-in-c-sharp-or-java and this http://www.codeproject.com/Articles/11939/Evaluate-C-Code-Eval-Function http://www.ckode.dk/programming/eval-in-c-yes-its-possible/ – Amr Elgarhy Oct 26 '14 at 18:16

2 Answers2

2

As far as I know, there's nothing like eval() built into C#.

For your purposes, though, given the code you've posted above, this would be better done by creating an IEnumerable of objects. Instead of saying:

for (int i = 0; i < MAX; i++)
{ 
    // does not work as written
    ("FullReservationDataControl" + i.ToString()).SetData(Reservation)
}

create and keep reference to a collection of your controls like so:

List<FullReservationDataControl> fullResDataControls = new List<FullReservationDataControl>() 
    { 
        /* add all your FullReservationDataControls here */ 
    };

then loop through it:

foreach (FullReservationDataControl resControl in fullResDataControls)
{
    resControl.SetData(Reservation);
}
furkle
  • 5,019
  • 1
  • 15
  • 24
0

You could use Reflection and invoke the SetData method on an object identified by a name (string).

References: Reflection: How to Invoke Method with parameters

I particularly like this approach:

How do I use reflection to invoke a private method?

static class AccessExtensions
{
    public static object Call(this object o, string methodName, params object[] args)
    {
        var mi = o.GetType ().GetMethod (methodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance );
        if (mi != null) {
            return mi.Invoke (o, args);
        }
        return null;
    }
}

Sample use in your case:

(someResultOfSearchByName as someExpectedType).Call("SetData", Reservation);

Sorry for the "some", but you gave no hint if this is a WinForms or WPF app.

Community
  • 1
  • 1
Darek
  • 4,687
  • 31
  • 47