JS like enumaration in C#

In JavaScript I can have an array of different objects in each cell, and when enumerating it each cell will get treated as the object it is and not as an underlying common object of the collection.

Lets say I have 2 objects:

class car
{
    public color;
    ...
}

class paint
{
    public color;
    ...
}

Is there a syntax for an enumaration like

car beemer;
paint panda;
...
foreach (thing in [beemer, panda])
{
    thing.color = "red";
}

in c#?

Jon Skeet
people
quotationmark

Well, you can use dynamic typing if you really want:

public class Paint
{
    public string Color { get; set; }
}

public class Car
{
    public string Color { get; set; }
}

...

var objects = new object[]
{
    new Car { Color = "Red" },
    new Panda { Color = "Black" }
};
foreach (dynamic value in objects)
{
    Console.WriteLine(value.Color);
}

But it would be more conventional to declare an interface with the property you want, and then make all the relevant types implement the interface:

public interface IColored
{
    string Color { get; set; }
}

public class Paint : IColored
{
    public string Color { get; set; }
}

public class Car : IColored
{
    public string Color { get; set; }
}

...

var objects = new IColored[]
{
    new Car { Color = "Red" },
    new Panda { Color = "Black" }
};
foreach (IColored value in objects)
{
    Console.WriteLine(value.Color);
}

This is:

  • More efficient
  • Safer, as then you know at compile-time that every value you're iterating over has a Color property.

people

See more on this question at Stackoverflow