Skip to content

Instantly share code, notes, and snippets.

@iSynaptic
Last active August 29, 2015 14:21
Show Gist options
  • Save iSynaptic/8e9fe746f47d496fe3df to your computer and use it in GitHub Desktop.
Save iSynaptic/8e9fe746f47d496fe3df to your computer and use it in GitHub Desktop.
C# Inference Scenario
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ScratchPad2015
{
class Program
{
static void Main(string[] args)
{
var id = new CustomerId();
IRepository repo = new Repository();
// type argument should (can?) be infered as Customer
Customer c = repo.Get(id);
// type argument and local variable should (can?) be infered as Customer
var c2 = repo.Get(id);
}
}
public interface IRepository
{
// T should (can?) be infered by right side of TId constraint
// TId can be infered from the callsite and since it can have and
// must have only one Id`1 class in its inheritance chain, T should
// be inferable from the callsite argument as well
T Get<TId, T>(TId id)
where TId : Id<T>;
}
public abstract class Id<T> { }
public class Repository : IRepository
{
public T Get<TId, T>(TId id) where TId : Id<T>
{
Console.WriteLine($"Id type is {typeof(T).Name} and return type is {typeof(TId).Name}.");
return default(T);
}
}
public class CustomerId : Id<Customer> { }
public class Customer { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment