6

I have the following generic class:

class Foo<T>
{
    //Constructor A
    public Foo(string str)
    {
        Console.Write("A");
    }

    //Constructor B
    public Foo(T obj)
    {
        Console.Write("B");
    }
}

I want to create an instance of this class with T being a string, using constructor B.

Calling new Foo<string>("Hello") uses constructor A. How can I call constructor B (without using reflection)?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Bip901
  • 590
  • 6
  • 22
  • Why not write your constructors to be less ambiguous? – Heretic Monkey Aug 11 '21 at 17:10
  • @HereticMonkey This is a stripped-down scenario to illustrate the problem; I have a real need for a similar setup. – Bip901 Aug 11 '21 at 17:41
  • In case the type string is not used explicitly but a generic type is used there as well, constructor B would be used in all cases. See my answer here: https://stackoverflow.com/a/65939872/101087 – NineBerry Aug 11 '21 at 17:47

2 Answers2

12

Since the two constructors use different names for the arguments, you can specify the name of the argument to choose the constructor to use:

new Foo<string>(str: "Test"); // Uses constructor A

new Foo<string>(obj: "Test"); // Uses constructor B
NineBerry
  • 26,306
  • 3
  • 62
  • 93
8

It's horrible, but you could use a local generic method:

public void RealMethod()
{
    // This is where I want to be able to call new Foo<string>("Hello")

    Foo<string> foo = CreateFoo<string>("Hello");

    CreateFoo<T>(T value) => new Foo(value);
}

You could add that as a utility method anywhere, mind you:

public static class FooHelpers
{
    public static Foo<T> CreateFoo<T>(T value) => new Foo(value);
}

(I'd prefer the local method because this feels like it's rarely an issue.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194