A calling constructor with a common parameter instead of an explicit

I assume this question is duplicated. But I could not find this question on SO

I want to instantiate a class. But if there is a constructor with an Explicit parameter AND the general constructor also has this parameter because of the given type, a constructor with an explicit parameter is used.

Example

 class Program
 {
    static void Main(string[] args)
    {
       Example<string> test = new Example<string>("test");
       test.Print();//Prints test2
    }
 }

 class Example<T>
 {
    private object Value;

    public Example(T value1)
    {
       this.Value = value1 + "1";
    }

    public Example(string value2)
    {
       this.Value = value2 + "2";
    }

    public void Print()
    {
       Console.WriteLine(Value as string);
    }
 }

Is there a way to call a generic constructor?

+4
source share
1 answer

You can use the syntax as shown below with named parameters:

Example<string> test = new Example<string>(value1: "test");

An important trick here is to have different parameter names, as you currently have, so it will display the right constructor from the parameter name, and the code will look like this:

using System;

public class Program
{
   public static void Main()
   {
      Example<string> test = new Example<string>(value1: "test");
      test.Print();//Prints test1
   }

class Example<T>
{
    private object Value;

    public Example(T value1)
    {
       this.Value = value1 + "1";
    }

    public Example(string value2)
    {
        this.Value = value2 + "2";
    }

    public void Print()
    {
          Console.WriteLine(Value as string);
       }
    }   
}

.

+5

Source: https://habr.com/ru/post/1678135/


All Articles