Uriel Salzar Uriel Salzar - 5 months ago 27
C# Question

Generic Method with a Generic Class in c#

I would like to know if there is a simple way in which I can simplify creating a Generic Method that takes a Generic Abstract Class.
It looks like this:

public J Read<T, M, J>(string fileName) where T : FileAccess<M, J> where M : Accessor where J : new() {
/*More Code... return J*/

The FileAccess Class takes the same generic "arguments".

public abstract class FileAccess<T, M> : IDisposable where T : Accessor where M : new() {/* More Code*/}

And there are other classes implementing this abstract class. e.g.

public class StateAccess : FileAccess<XMLAccessor, List<Data>> {/*More Code*/}

Most of the times C# is clever enough to figure it out the other generic types you're using, so you don't have to write them. I thought it would work the same and it would end up something like this:


But instead this is what I have to do in order to make it work:

Read<StateAccess, XMLAccessor, List<Data>>("state");

Even though I already made a Class StateAccess that uses XMLAccessor and a List of Data.

The Method Read will be used with other classes that inherits from FileAccessor.
So my question is: How can I make my code work so I end up with this?


Thank you in advanced.


René's comment is correct- you cannot infer a subset of generic arguments here.

What you can do (assuming that your method Read doesn't do anything with the generic type M) is something like this:

interface IReadableFileAccess<J> { ... // methods that Read needs... }

Then make FileAccess or StateAccess implement IReadableFileAccess and change the signature of Read to:

J Read<J>(IFileAccess<J> access, String fileName,  ... whatever ...) { ... }

To which you can just pass an instance of StateAccess, which is closed for J:

Read(someStateAccess, "fileName")

Note: "Closed for J" above means that StateAccess is not generic for J- the type for J is specified and therefore inferable.