I have a collection containing variables I want to print the names of the variable in this collection
Advantage, you can do this whether you "own" the class or not.
Option 2 - Use an interface
to guarantee the properties exist
Define an interface that has the desired properties and accessibility.
interface INameAndValueProvider
{
string Name { get; }
object Value { get; }
}
If minimal classes (for example) implement the interface like this:
class ClassA : INameAndValueProvider
{
public string Name { get; set; } = "A";
public object Value { get; set; } = 1;
}
class ClassB : INameAndValueProvider
{
public string Name { get; set; } = "B";
public object Value { get; set; } = "Hello";
}
class ClassC : INameAndValueProvider
{
public string Name { get; set; } = "C";
public object Value { get; set; } = Math.PI;
}
You can make an object[] containing one of each:
var collection = new object []
{
new ClassA(),
new ClassB(),
new ClassC(),
};
Now iterate the collection, using an implicit cast to INameAndValueProvider
.
foreach (INameAndValueProvider item in collection)
{
Console.WriteLine("variable name: " item.Name);
Console.WriteLine("variable value: " item.Value);
Console.WriteLine("variable type : " item.GetType().Name);
Console.WriteLine("***************************** ");
}