2

I have strings with a math function names. E.g. Sin, Abs, Max ...

How can I call for example Math.Sin(arg) in a way where I can specify the Sin part based on a variable?

6
  • Did you try reflection? Commented Apr 18, 2020 at 13:00
  • Have you take a look at extension methods? Commented Apr 18, 2020 at 13:00
  • No, I just started C#. Do you have an entry point/link? Commented Apr 18, 2020 at 13:01
  • 2
    You could use reflection, but for a simple case like choosing the function from a set, it is simpler to use a switch statement. Commented Apr 18, 2020 at 13:01
  • 1
    You wrote in your comment Do you have an entry point/link? Is there something preventing you from searching the Internet? C# Reflection and C# Extension Methods Commented Apr 18, 2020 at 13:05

1 Answer 1

2

You Can use reflection

var concreteType = typeof(Math);
var result = concreteType.GetMethod("Sin").Invoke(null, new object[] { numbers });
Sign up to request clarification or add additional context in comments.

1 Comment

Since Math.Sin is a static method, you must .Invoke(null, ...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.