Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

234
Vistas
How to call a constructor with an ambiguous generic parameter?

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)?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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.)

over 4 years ago · Santiago Trujillo Denunciar

0

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
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda