How to make nested common classes (if appropriate name) in csharp

I would like to create a class of the following type

public class EnumerableDisposer<IEnumerable<IDisposable>> 

But this will not allow me to state this in this way. I also tried:

 public class EnumerableDisposer<T> : IDisposable where T : IEnumerable<J> where J : IDisposable 

But the compiler tells me that the type / namespace J cannot be found.

What do I need to do to create this class?

+6
generics c # class
source share
3 answers

You need to do:

 public class EnumerableDisposer<T, J> : IDisposable where T : IEnumerable<J> where J : IDisposable { // Implement... 

Unfortunately, in order to wrap any internal type ( IEnumerable<J> in your code), your "wrapping" class must have type J defined in the general definition. Also, to add an IEnumerable<J> constraint, you need to have a different type T

If you want to avoid the dual generic type specification, you can always rework it as follows:

 public class EnumerableDisposer<T> : IDisposable where T : IDisposable { public EnumerableDisposer(IEnumerable<T> enumerable) { // ... 

This forces you to build it using IEnumerable<T> , where T is IDisposable, with one common type. Since you are effectively adding an IEnumerable<T> constraint through the constructor, this will work the same as the previous option. The only drawback is that you need the overall result to be executed during construction, but given the name, I suspect that everything will be fine ...

+12
source share

you need to define J .

eg,

 public class EnumerableDispose<T, J> : IDisposable where T : IEnumerable<T> where J : IDisposable 

it would be better:

 public class EnumerableDispose<T> : IEnumerable<T>, IDisposable where T : IDisposable { public EnumerableDispose(IEnumerable<T> source) { // TODO: implement } } 
+5
source share

You can do this by adding an additional parameter of type J :

 public class EnumerableDisposer<T, J> : IDisposable where T : IEnumerable<J> where J : IDisposable 

Note that these parameters T and J are independent of any parameters in the outer class, even if they have the same name.

0
source share

All Articles