Recently, I had to create a generic function. This generic function should be able to take in a generic type and execute code based on the generic type passed into the function and then return the same type as the result.
Consider the function below as an example for the above:
So if string is passed into the function as T, the function should execute some code which will consequently return a string like shown in a sample use below:
And if a user-defined type is passed as T into the function, it should execute a different set of code and return an object of the same user-defined type as shown below:
After much research & deliberation, I ended up with the following code to solve the problem:
Bear in mind that this solution leverages on pattern matching; which is only available in C# version 7 and onwards. It will not work on older versions of C#.
It may not be the best approach but it is what I could come up with for now. I am open to suggestions for improvements.