-1

I have to make extensions for all types arrays of numbers : ints, longs, floats, doubles, etc. that can do some things. Of course, I could do it for every type of integers, but that would look ugly.

double GetSomeValue (int[] array)
{
// some code
}

double GetSomeValue (double[] array)
{
// some code
}
etc, etc...       

Is there any nice way to make in a short manner ?

CodingGorilla
  • 19,612
  • 4
  • 45
  • 65
Imugi
  • 161
  • 1
  • 3
  • 13
  • have you considered generics? please post what you are going to be doing in the methods. – Daniel A. White Mar 19 '16 at 00:17
  • Specify *what* the methods shall *specifically* do. – Ondrej Tucny Mar 19 '16 at 00:18
  • 3
    Most probably the answer is no. There isn't a particularly useful generic constraint that would cover these types. (I'm assuming that you're trying to get the average value of the values in the array or something similar.) – Theodoros Chatzigiannakis Mar 19 '16 at 00:19
  • I have to calculate different kind statistical values, e.g. standard deviation. – Imugi Mar 19 '16 at 00:21
  • 1
    @Imugi Unfortunately, generics are essentially out of the question because these types don't share any common interface that would enable you to perform the necessary operations to calculate standard deviation (and C# doesn't support "or" in the constraints). T4 templates are a good compromise (see the answer). Using the `dynamic` keyword is also another compromise you can use to avoid code duplication, but it will have a runtime performance impact. – Theodoros Chatzigiannakis Mar 19 '16 at 00:27

1 Answers1

3

Short answer is no. Depending on what you are actually trying to do you can use generic method declaration but it will accept broader set of types, cause there is no way to restrict generic method to accept only numeric types in C#.

Also an option would be using T4 Templates like here

Community
  • 1
  • 1
Guru Stron
  • 102,774
  • 10
  • 95
  • 132