Introduction
Generic Math provides you the ability to use arithmetic operators on generic types. This support is also known as abstracting over static members. In this blog, you will learn how to implement generic math with abstraction over static members.
Pre-requisite
C# 11
What is the Generic Math function in C#?
Assume the below method,
public static int AddInt(int left, int right) => left + right;
The AddInt function will add only the two integer values passed as an input parameter for the function and return the result.
For example, if we call AddInt using the below statement, you will get a result of 30.
var result = AddInt(10, 20);
If you try to pass any one or both parameter values as double, you will get an error message “Cannot convert double to int”. So, to overcome this, we use to create a new function to perform the addition of two numbers.
public static double AddDouble(double left, double right) => left + right;
Now, you will be ended up having two methods. One is to perform the addition of two integers, and the other is the addition of two double values.
So, we can convert this method to generic with generic math support C#.
public static T Add<T>(T left, T right) where T : INumber<T> => left + right;
This generic method will give you the result for any number value; it can be an integer or double. In this Add method type parameter T is constrained to be a type that implements the new INumber<TSelf> interface.
Add(10, 20); //30
Add(10, 20.5); //30.5
Summary
We have seen how to implement the generic math with abstraction over static members; with this generic math support, we defined the generic add function.