Rafael Rafael - 1 month ago 6
C# Question

c# implicit operator a matrix with parameters

I have this class:

public class SmartTable : DataTable
{
public string this[int Row, int Column] { ... }
public string this[int Row, string Column] { ... }
}


and i want to add an implicit operator on THIS[,]

then i could use:

string s = smartT[a,b];


or

int i = smartT[a,b];


I googled this but even I don't know how to search it.

I tried (based on IntelliSense) declare something like:

public static implicit operator int[int r, int c](...) {...}


or

public static implicit operator int (SmartTable sm, int a, int b)


and don't work.

Thanks

=== Edit ===

This is a DataTable, and a table have strings, integers, ...

I want to avoid put Convert.To--(...) every time i use this table...

If I try to put a Field on a int, is because it's a integer field...
A solution I'm using is create iGet(int C, int R), sGet(...), dGet(...)

Answer

If you can change your SmartTable design to return or work with a custom class instead of the primitive string type, then you can add your own implicit conversions to int or string.

public class SmartTable : DataTable
{
    //dummy/hard-coded values here for demonstration purposes
    public DataValue this[int Row, int Column]  { get { return new DataValue() {Value="3"}; } set { } }
    public DataValue this[int Row, string Column]  { get { return new DataValue() {Value="3"}; } set { } }
}

public class DataValue
{
    public string Value;

    public static implicit operator int(DataValue datavalue)
    {
        return Int32.Parse(datavalue.Value);
    }

    public static implicit operator string(DataValue datavalue)
    {
        return datavalue.Value;
    }
}

And some usage:

string s = smartT[0, 0];
int i = smartT[0, 0];

Console.WriteLine(s);//"3"
Console.WriteLine(i);//3

Note that this kinda flies in the face of using implicit operators. For example, if your DataValue.Value is non-convertable to int (for example, if it were "Hello World!") it would throw an exception which is generally against the best practices and unexpected for developers leveraging your API.