views:

42

answers:

3

I would like to know if (and if so how) it is possible to define a namespace as a constraint parameter in a generic class declaration.

What I have is this:

namespace MyProject.Models.Entities <-- Contains my classes to be persisted in db

namespace MyProject.Tests.BaseTest <-- Obvious i think

Now the decleration of my 'BaseTest' class looks like so;

public class BaseTest<T>

This BaseTest does little more (at the time of writing) than remove all entities that were added to the database during testing. So typically I will have a test class declared as:

public class MyEntityRepositoryTest : BaseTest<MyEntity>

What i would LIKE to do is something similar to the following:

public class BaseTest<T> where T : <is of the MyProject.Models.Entities namespace>

Now i am aware that it would be entirely possible to simply declare a 'BaseEntity' class from which all entities created within the MyProject.Models.Entities namespace will inherit from;

public class BaseTest<T> where T : MyBaseEntity

but...I dont actually need to, or want to. Plus I am using an ORM and mapping entities with inheritance, although possible, adds a layer of complexity that is not required.

So, is it possible to constrain a generic class parameter to a namespace and not a specific type ?

+4  A: 

It's not possible to create any such constraints to namespaces.

A more preferable workaround would be to make your generic class internal rather than public. This means that the class can only be directly instantiated and accessed by classes in the same assembly (unless you use the InternalsVisibleTo attribute). However, it can still be indirectly instantiated (i.e. as a protected/private member of a public class).

Mark Rushakoff
Agreed. And, if the type you want to permit is in a different assembly then look into `InternalsVisibleToAttribute`. I use this with unit tests in different assemblies regularly.
Drew Noakes
That is a shame, im surprised you cannot do something with lambda expressions or something. Not to worry, that 'internal' solution meets my needs half-way. Thank you for the guidance.
SomeGuy
@SomeGuy, as far as I know, lambdas are still only a runtime thing (except for when used with Expressions, but even then they're not executable at compile time). There's been some discussion about whether the prospective C# 5.0 compiler-as-a-service feature might allow some customisation of the compiler, though I have my doubts if we'll ever see that.
Drew Noakes
+1  A: 

The compiler won't perform this check for you. You could verify this constraint at runtime though, perhaps in a static constructor for your type.

Drew Noakes
A: 

A namespace constraint would be of no value. Any third party could create a class and put that class into the same namespace.

John Saunders