Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace constraint with generic class declaration

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 ?

like image 929
SomeGuy Avatar asked Jun 13 '10 13:06

SomeGuy


2 Answers

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).

like image 164
Mark Rushakoff Avatar answered Oct 20 '22 20:10

Mark Rushakoff


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

like image 33
John Saunders Avatar answered Oct 20 '22 19:10

John Saunders