tags:

views:

80

answers:

2

I have a generic Print method that iterates over a list and simply prints each item's file name

    private static void Print<T>(
        Func<IEnumerable<T>> getFiles, Func<T, string> getFileName) 
            where T : class 
    {
        foreach (T file in getFiles())
        {
            var fileName = getFileName(file);
            Console.WriteLine("File Name: {0}", fileName);
        }
    }

For the method to know what the type of T is I can call Print in two different ways

 Print<FileInfo>(FileFinder.GetFiles, fileInfo => fileInfo.FullName);

-- or --

 Print(FileFinder.GetFiles, (FileInfo fileInfo) => fileInfo.FullName);

What would be a correct way to call Print method?

Specify generic type explicitly or let the compiler infer it?

+1  A: 

Either option is fine.

I personally prefer allowing the compiler to infer the types when possible. There is no real need to include that in your source code, but the end result, in IL, will be identical.

Reed Copsey
Marked as Answer: Answer => Either option is fine, "IL, will be identical" => concrete reason to back up the answer.@Reed: thank you for the answer.
Sung Meister
You're welcome to mark whatever answer you like, but I am always surprised when people mark an answer to an open-ended question less than 30 minutes after the question is asked. Who knows how many great answers will appear over the next few hours? Why so quick to judge?
Brian
Ah, I wanted to just move on.
Sung Meister
+1  A: 

I would tend to prefer the second one. In general, there's no guarantee that the generic parameters to Print have any reasonable relationship with the Func parameter argument. That is given

Foo<T>(yadda, (bar) => body)

there is no reason to think that "T" and "bar" are related. Whereas

Foo(yadda, (T bar) => body)

you know that bar is a T. Additionally, for cases where T and bar are related, if yadda is long, you put a lot of physical distance between T and bar, which increases the cognitive burden of the reader.

Brian
+1 for cognitive burden
Sung Meister