Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write overloaded generic extension methods for T[], T[][] without ambiguity?

I want to write extension methods for converting a vector and matrix into string. I did this in the following way.

For Vector

public static string GetString<T>(this T[] SourceMatrix, string ColumnDelimiter = " ")
{
    try
    {
        string result = "";
        for (int i = 0; i < SourceMatrix.GetLength(0); i++)
            result += SourceMatrix[i] + ColumnDelimiter;
        return result;
    }
    catch (Exception ee) { return null; }
}

For Matrix

public static string GetString<T>(this T[][] SourceMatrix, string ColumnDelimiter = " ", string RowDelimiter = "\n")
{
    try
    {
        string result = "";
        for (int i = 0; i < SourceMatrix.GetLength(0); i++)
        {
            for (int j = 0; j < SourceMatrix[i].GetLength(0); j++)
                result += SourceMatrix[i][j] + "" + ColumnDelimiter;
            result += "" + RowDelimiter;
        }
        return result;
    }
    catch (Exception ee) { return null; }
}

Now i am using following code which causes ambiguity.

List<double[]> Patterns= GetPatterns(); 
Patterns.ToArray().GetString();

Error

Error   5   The call is ambiguous between the following methods or properties: 
'MatrixMathLib.MatrixMath.GetString<double[]>(double[][], string)' and 
'MatrixMathLib.MatrixMath.GetString<double>(double[][], string, string)'    

Can anyone suggest me to write these extension methods correctly.

Thanks in advance.

like image 211
Rajeev Avatar asked Aug 03 '14 08:08

Rajeev


1 Answers

There is nothing wrong with your methods. It is the compiler that can't choose between them.

As you can see in the error message, the compiler could assume T to be double[] and match the first method, or double and match the second one. This will be solved by explicitly mentioning which method you want to use:

Patterns.ToArray().GetString<double>();
like image 160
Alireza Avatar answered Oct 12 '22 16:10

Alireza