Looping Thru C# Objects - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Looping Thru C# Objects

win2333win2333 Posts: 1Member
I just want to ask if you guys could dish out some codes on how to loop objects in C#. Thanks in advance..

Comments

  • ShugShug Posts: 2Member
    : I just want to ask if you guys could dish out some codes on how to loop objects in C#. Thanks in advance..
    :

    C# implements:
    [code]
    [blue]foreach[/blue] [object] [blue]in[/blue] [object]
    [/code]

    So, find the derived objects that belong to an object (like the controls belonging to, or the properties for the object you want to loop through), and code each case.

    Eg. [code][blue]if[/blue]([object]==System.Windows.Forms.Textbox){[green]/*stuff*/[/green]}[/code]

    Hope that helps your cause.

    Hugh
  • BaldusariusBaldusarius Posts: 162Member
    : So, find the derived objects that belong to an object (like the controls belonging to, or the properties for the object you want to loop through), and code each case.
    :
    : Eg. [code][blue]if[/blue]([object]==System.Windows.Forms.Textbox){[green]/*stuff*/[/green]}[/code]
    :

    Actually, this wouldn't even compile. The "==" operator requires a variable, not a type. You could test to see if "object" is a TextBox by using [code]if(object.GetType() == typeof(TextBox))[/code] but that wouldn't test for derivation, only equality.

    To find out if an object is derived from a particular class, you'd use [code]if(object is TextBox)[/code]

    Charlie


  • BaldusariusBaldusarius Posts: 162Member
    : I just want to ask if you guys could dish out some codes on how to loop objects in C#. Thanks in advance..
    :

    If the collection of object you're enumerating implements ICollection, you can use [blue]foreach[/blue]
    [code]foreach(Foo foo in Foos)
    {
    Manipulate(foo);
    }[/code]

    If the collection features an indexer, you can use it to traverse the collection
    [code]for(int i = 0; i < 10; i++)
    {
    Manipulate(Foos[i]);
    }[/code]

    Charlie

Sign In or Register to comment.