2

In VS2015:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TypeInference
{
    public interface IResolvable<T>
    {
        T Resolve();
    }

    public class Trivial<T> : IResolvable<T>
    {
        private T it;
        public T Resolve() { return it; }

        public Trivial(T the) { it = the; }
    }

    public class TrivialText : Trivial<string>
    {
        public TrivialText(string s) : base(s) { }
    }

    class Program
    {
        static string f(IResolvable<string> s)
        {
            return s.Resolve();
        }

        static void Main(string[] args)
        {
            string s = "yet another string";

            // error CS0305: Using the generic type 'Trivial<T>' requires 1 type arguments
            Console.WriteLine(f(new Trivial("this is a string, right?")));
            Console.WriteLine(f(new Trivial(s)));
            // ok
            Console.WriteLine(f(new Trivial<string>("this is a string, right?")));
            // OK
            Console.WriteLine(f(new TrivialText("this is a string, right?")));
        }
    }
}

It seems like the type inference here should be obvious. The first two lines are clearly taking a string, but both forms insist I declare the type parameter. This seems contradictory to the statement made here:

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-methods

You can also omit the type argument and the compiler will infer it. The following call to Swap is equivalent to the previous call

Am I doing something wrong?

TIA

Brad
  • 3,190
  • 1
  • 22
  • 36
  • 2
    The link you added is about generic method. What you're trying to do is infer generic type in a constructor call. That's not supported in C#. – MarcinJuraszek Feb 25 '18 at 02:49
  • 1
    IIRC Try `static Trivial Create(T value) => new Trivial(value);` While Type inference doesn't work on constructors, it does work on methods. – NPSF3000 Feb 25 '18 at 02:51
  • @MarcinJuraszek - Thanks - I naively consider constructors to be methods - just a particularly special sort. But your answer clarifies. Thanks! – Brad Feb 25 '18 at 23:29
  • 1
    If you want a language with type inference in more places than C#, maybe try F#. I implemented your example in F# to show where types need to be annotated, and where they will be inferred (https://pastebin.com/R4Zud3JZ). Here, constructors are indeed used as if they were normal functions. – dumetrulo Feb 26 '18 at 10:16
  • @dumetrulo - thanks. As I'm working in an existing codebase, switching language isn't an option for me, but thanks for taking the time to create the example. – Brad Feb 26 '18 at 18:29

0 Answers0