none
Contraining a generic type to non-array RRS feed

  • Question

  • I have defined a generic function like:

            private static T[] Apply<T>(T[] x, applyfunc<T> f)
            {
    

    The works fine for "normal" types specfied in T. But the compiler gives me no warning when I try something like:

                double[][] xa = { new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
                                  new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
                                  new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
                                  new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } };
                double[][] ra = BsiUtility.Apply(xa, a => a);
    

    So I would like to add a constraint to eliminate the array types. In other words I don't want T to be something like T[] or T[][] or T[,]. I have tried various forms of the constraint clause (where . . . ) but have yet to hit upon a solution. Is this possible?

     

    Thank you.

     

    Kevin

    Friday, March 19, 2010 5:07 PM

Answers

  • I don't think that C# or VB support that. Your best choice is either runtime check, or debug-only runtime assert.

    -Karel

    • Marked as answer by KevinBurton Friday, March 19, 2010 10:13 PM
    Friday, March 19, 2010 10:05 PM
    Moderator

All replies

  • There is no way to exclude a type in a constraint. About the only thing you can do is throw an exception at runtime:

    if (x is Array)
        throw new NotSupportedException("Array types are not allowed.");

    Friday, March 19, 2010 5:18 PM
  • Thank you. I already have this exception thrown. I was just hoping that the compiler could warn me/the user before runtime.

    Kevin

     

    Friday, March 19, 2010 5:41 PM
  • I don't think that C# or VB support that. Your best choice is either runtime check, or debug-only runtime assert.

    -Karel

    • Marked as answer by KevinBurton Friday, March 19, 2010 10:13 PM
    Friday, March 19, 2010 10:05 PM
    Moderator