C# 11 – Generic Math Support

Introduction:

  The Generic Math support is also known as abstracting over static members. As the name indicates, it’s obvious that now you can declare static abstract methods as part of an interface and implement them in the derived types. In this blog you will learn how the C# 11 support to implement generic math with abstraction over static member.

Generic Math Support:

Assume the below function AddInt, this will take the integer array as an input and returns a result by adding all the values in the array.  

public int AddInt(int[] values)
        {
            int result = 0;
            foreach (int value in values)
            {
                result += result;
            }
            return result;
        }

There won’t be any issue if the input elements in the array is an integer.  

int[] ints = {1,2,3,4};

If there is a double element within an input array, we will get a compiler error and it will encourage to write a new function to Add the double elements in the array.

So, we need to write a new function to process the double array, as given below.  

double[] ints = {1,2,3,4.5};
var result=AddDouble(ints);
        public double AddDouble(double[] values)
        {
            double result = 0;
            foreach (double value in values)
            {
                result += result;
            }
            return result;
        }

So, now we have two functions one to process the integer array and another one to process the double array.

With C# 11 we can convert it to Generic method to perform an action based on any type of input.

  public T AddAll<T>(T[] values) where T: INumber<T>
        {
            T result = T.Zero;

            foreach(var value in values)
            {
                result += value;
            }
            return result;
        }

Now, the above function is a Generic function to sum of integer or double array elements. With C# 11 we can use T is a INumber, with this we can use T.Zero which is a static abstract member of INumber.

Accessing the Generic math function


var genericMath = new GenericMath();
var allNumbers = new[] { 1, 2, 3, 4.5 };
var result = genericMath.AddAll(allNumbers);
Console.WriteLine("----Generic Math----");
Console.WriteLine($"Sum of the array elements {result}");

Output:

Summary:

  We have seen what is the Generic math and how it is supported by C# with static abstract member in interface. We will more feature available in C# 11 in my future blogs.

Happy Coding 🧑‍💻

Source code – download

gowthamk91

Leave a Reply

%d bloggers like this: