0

I am trying to write a matrix class in C#, and want to cover just integral types. Yes, I know, there are probably a bunch of other libraries out there that provide this functionality already - I just wanted to give it a try myself to apply some of the math I'm learning in school.

Anyway, the real problem here: I have my constructor:

public class Matrix {
    private int[,]    __matrix;

    Matrix(int rows, int columns) {
        /* ... some logic here ... */
        __matrix = new int[row , columns];
    }
}

I know you can constrain to just structs, but that also means that things like DateTime could end up in the matrix. Any suggestions on how to solve this, or has anyone seen this done elsewhere? I was thinking of writing a generic class, but I'm almost leaning on an attribute that declares allowable types, and then just checking that attribute in code at this point, but am also not at all stoked about the prospect of the boxing/unboxing overhead of using an object[] for my matrix.

halfer
  • 19,824
  • 17
  • 99
  • 186
PSGuy
  • 653
  • 6
  • 17
  • 1
    You can make a generic class. Then, make a simple check for type in your constructor and throw `IllegalArgumentException` if it is not suitable. I am not sure if it is a good practice, but I would do it this way. – Yeldar Kurmangaliyev Nov 19 '15 at 05:14
  • 1
    Unfortunately, there is no way to restrict generic types to only primitive numeric types in C# :( – MarcinJuraszek Nov 19 '15 at 05:14
  • Okay. That's sort of what I gathered reading the MSDN documentation too, but was hoping that maybe someone else had some experience with it. Thank you for the responses. Does someone want to post an answer I can mark? – PSGuy Nov 19 '15 at 05:24

1 Answers1

0

You won't be able to simply restrict to Int32, or any of these primitive numeric types.

Take a look at this question: Is there a constraint that restricts my generic method to numeric types?

The workaround seems way more complicated than we would expect. Deferring arithmetic operations to some other generic class...

Read on for more details.

Community
  • 1
  • 1
DDan
  • 8,068
  • 5
  • 33
  • 52