2

I want to get all classes from namespace so I have used this code:

var theList = Assembly.GetExecutingAssembly().GetTypes()
                  .Where(t => t.Namespace == myNameSpace)
                  .ToList();

It's working but when I'm looping through this list, I want to create instance or call constructor of each class in theList list and for example call their methods or properties.

Ofc this code is not working, but this is my purpose.

foreach (Type t in theList)
        {
            description += t.Description;
        }

@Edit I did:

        var theList = Assembly.GetExecutingAssembly().GetTypes()
              .Where(t => t.Namespace == myNameSpace)
              .ToList();

        foreach (Type t in theList)
        {
            Command instance = (Command)Activator.CreateInstance(t);
            result += Environment.NewLine + instance.Name + " - " + instance.Description;
        }
Porqqq
  • 65
  • 6

1 Answers1

0

To create an instance of a class you can call Activator.CreateInstance().

Thereis also a nice extension method that I use to get properties and values from objects:

/// <summary>
///     Gets all public properties of an object and and puts them into dictionary.
/// </summary>
public static IDictionary<string, object> ToDictionary(this object instance)
{
    if (instance == null)
        throw new NullReferenceException();

    // if an object is dynamic it will convert to IDictionary<string, object>
    var result = instance as IDictionary<string, object>;
    if (result != null)
        return result;

    return instance.GetType()
        .GetProperties()
        .ToDictionary(x => x.Name, x => x.GetValue(instance));
}
Dmitri Trofimov
  • 753
  • 3
  • 14