Retrieving all namespace classes

What are the different ways to achieve reflection in C#? There are a few solutions available. One solution involves using LINQ, while another solution does not require LINQ. Another option is to refer to a question on how to get all classes within a namespace. Is it possible to instantiate all classes in a namespace without reflection in C#? This question arises when there is a list of script classes.

Question:

How can I use reflection in C# to obtain the

List

for every class within a specific namespace?


Solution 1:

var theList = Assembly.GetExecutingAssembly().GetTypes()
                      .Where(t => t.Namespace == "your.name.space")
                      .ToList();


Solution 2:

Without LINQ:

Try:

Type[] types = Assembly.GetExecutingAssembly().GetTypes();
List myTypes = new List();
foreach (Type t in types)
{
  if (t.Namespace=="My.Fancy.Namespace")
    myTypes.Add(t);
}


Solution 3:

Review this post on obtaining all classes within a namespace. The solution shared yields an array of Type[], which can be adjusted to return a List with ease.


Solution 4:

The only solution that comes to mind is to iterate through the types within an assembly and identify the ones that belong to the desired namespace.

public List GetList()
        {
            List types = new List();
            var assembly = Assembly.GetExecutingAssembly();
            foreach (var type in assembly .GetTypes())
            {
                if (type.Namespace == "Namespace")
                {
                    types.Add(type);
                }
            }
            return types;
        }

Frequently Asked Questions

Posted in Uncategorized