1

In Java I can declare a method like: public boolean doSth(Cache<?> cache, CacheItem item){...}

public interface Cache<T> {
    public boolean Contains(T item);
}

public class CacheFilePath implements Cache<FilePathItem> {
    @Override
    public boolean Contains(FilePathItem item) {
        return false; // TODO
    }
}

public class ItemHandler {

    public boolean doSth(Cache<?> cache, CacheItem item){
        if(cache instanceof CacheHostName && item instanceof HostNameItem){
            CacheHostName c = (CacheHostName) cache;
            HostNameItem i = (HostNameItem) item;
            return check(c, i);
        }
        else if(cache instanceof CacheFilePath && item instanceof FilePathItem){
            CacheFilePath c = (CacheFilePath) cache;
            FilePathItem i = (FilePathItem) item;
            return check(c, i);
        }
        throw new RuntimeException("Invalid arguments  !!!");
    }

    private boolean check(Cache<HostNameItem> cache, HostNameItem item){
        return cache.Contains(item);
    }

    private boolean check(Cache<FilePathItem> cache, FilePathItem item){
        return cache.Contains(item);
    }
}

How can I declare such a method in C#?

My-Name-Is
  • 4,814
  • 10
  • 44
  • 84
  • 1
    How is it that making the method generic *doesn't* solve your problem? Side note, it's generally code smell to make a method generic and then just switch through a bunch of derived types it could be and act on them. It's usually the case that you should just have N overloads, rather than a bunch of type checks and casts. – Servy Nov 26 '13 at 17:05
  • The issue would normally be avoided by the generic class implementing an interface that uses `object`, alongside the same methods using the specific type. If `Cache<>` doesn't do this and it isn't yours to modify, the closest you can get to the above code is to accept `object` and manually type check against `typeof(Cache<>)`. – nmclean Nov 26 '13 at 17:15

1 Answers1

2

You could declare a type parameter on the method like this:

public boolean doSth<T>(Cache<T> cache, CacheItem item){
    ...
}

Or use a non-generic base class or interface:

public interface ICache { ... }
public class Cache<T> : ICache { ... }

public boolean doSth(ICache cache, CacheItem item){
    ...
}
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331