Home > Back-end >  How to traverse an object that has more Objects inside and temporarily cast the type
How to traverse an object that has more Objects inside and temporarily cast the type

Time:01-16

I have the following code that runs through a GroupControl, natively in c # is called GroupBox, what I want to do is go through it internally and depending on the object that is I want to perform an action, for example:

foreach (Control item in groupControl1.Controls)
{
    MessageBox.Show(item.ToString());

    if (item is CalcEdit)
    {
        (CalcEdit)item = item.value=0
    }

    if (item is DateEdit)
    {
        (DateEdit)item = item.DateTime.now
    }
}

But I do not know the correct way to caste the object temporarily to obtain its properties and thus establish the value I want.

What would be suggestible?

CodePudding user response:

Here's one option:

foreach (Control item in groupControl1.Controls)
{
    MessageBox.Show(item.ToString());

    if (item is CalcEdit calcItem)
    {
        calcItem.Value = 0;
    }
    else if (item is DateEdit dateItem)
    {
        dateItem.DateTime = DateTime.Now;
    }
}

I've made some small adjustments because your code seems to make no sense but the pattern matching is the important part.

You could also do this:

foreach (var item in groupControl1.Controls.OfType<CalcEdit>())
{
    item.Value = 0;
}

foreach (var item in groupControl1.Controls.OfType<DateEdit>())
{
    item.DateTime = DateTime.Now;
}

The second option is less efficient because it enumerates the entire Controls collection twice but the difference will be insignificant as the number of items will be so small.

CodePudding user response:

The (excellent) answer of @jmcilhinney requires C# 7.0 or later. If, for some reason, you're limited to an earlier version (which lacks pattern matching), this slightly more cumbersome approach is an alternative:

CalcEdit calcEditItem = item as CalcEdit;
if (calcEditItem != null)
{
    calcEditItem.Value = 0;
}

DateEdit dateEditItem = item as DateEdit;
if (dateEditItem != null)
{
    dateEditItem.DateTime = DateTime.Now;
}
  • Related