views:

40

answers:

1

I am trying to find all of the types in the Models namespace within an ASP.NET MVC assembly from within a testing assembly. I was trying to use LINQ to find the relevant set for me but it is returning an empty set on me. I am sure it is some simple mistake, I am still relatively new to LINQ admittedly.

var abstractViewModelType = typeof (AbstractViewModel);
var baseAssembly = Assembly.GetAssembly(abstractViewModelType);
var modelTypes = baseAssembly.GetTypes()
    .Where(assemblyType => (assemblyType.Namespace.EndsWith("Models")
                           && assemblyType.Name != "AbstractViewModel"))
    .Select(assemblyType => assemblyType);

foreach(var modelType in modelTypes)
{
    //Assert some things
}

When I reach the foreach I receive a Null reference exception.

+1  A: 

To locate a NullReferenceException in a lot of code, you have to break it down to see what is coming back null. In your code, I only see one place where that's possible. Try this instead:

var abstractViewModelType = typeof (AbstractViewModel);
var baseAssembly = Assembly.GetAssembly(abstractViewModelType);
var modelTypes = baseAssembly.GetTypes()
    .Where(assemblyType => (assemblyType.Namespace != null // Problem if null
                           && assemblyType.Namespace.EndsWith("Models")
                           && assemblyType.Name != "AbstractViewModel"))
    .Select(assemblyType => assemblyType);

foreach(var modelType in modelTypes)
{
    //Assert some things
}
John Saunders
That was indeed it. I should have checked the documentation better. I know that strings can be null, but I wasn't expecting the possibility that the namespace could actually come back null.
Matt
@Matt: that's probably a type that is not in a namespace.
John Saunders
@John Saunders: when I looked closer that is exactly what was what it was. There were a couple anonymous classes that it was finding in the assembly.
Matt