tags:

views:

141

answers:

3

For example I now created a this tiny class:

public static class FileSystemInfoComparers<T> where T : FileSystemInfo
{
    public static IEqualityComparer<T> FullName
    {
        get { return new FullNameComparer(); }
    }

    private class FullNameComparer : IEqualityComparer<T>
    {
        public bool Equals(T x, T y)  { return x.FullName == y.FullName;   }
        public int GetHashCode(T obj) { return obj.FullName.GetHashCode(); }
    }
}

I would like it if I could just do

var comparer = FileSystemInfoComparers.FullName;

and have an instance of IEqualityComparer<FileSystemInfo>, since I didn't specify any type and FileSystemInfo is the most generic type T can be. With no type constraint the default type could for example be object or something.

Maybe not the best example, but anyways just got curious here :p

+1  A: 

That is an interesting idea and it could definitely work but consider that it would only work in cases where the generic type argument is constrained with a concrete type.

The .NET compilers are very good at type inference but tend to shy away from making any assumptions. I don't see any reason why this couldn't be done except that it would only work in a small number of highly-specific instances. Since it has no general purpose I would imagine that Microsoft would be less inclined to make a change to support it.

Andrew Hare
Not really: System.Collections.Generic.List<T> doesn't have a constraint, so System.Collections.Generic.List could be equivalent to System.Collections.Generic.List<object>
Niki
@Niki: Excatly my thought.
Svish
@Niki: Perhaps I should have said "it would only do something useful". A List<Object> is not particularly useful.
Andrew Hare
A: 

You could possible do this by having a helper class that has the default type you want set. But what you are asking for currently cannot be done in C# 3.0.

Nick Berardi
Hm, good idea actually... could maybe just create a class inheriting from it or something. Although that wouldn't be possible for static classes. And would require kind of rewriting various constructors etc for non-static ones...
Svish
+8  A: 

Sounds like a recipe for trouble to me.

In particular, you could easily create a non-generic class called FileSystemInfoComparers with a static property of the same name, and suddenly your code would mean something completely different.

I'd rather keep things simple. (Generics are complicated enough already, and type inference in particular is pretty hairy.)

Jon Skeet
"Sounds like a recipe for trouble to me.". That tickled our dev department, keep those one-liners coming Jon :-) +1
DoctaJonez
Good point. And +1 for one-liner :p
Svish