C# automatic casting when calling overloaded function -


let's imagine have following overloaded function:

void dosomething(int x) { ... } void dosomething(float x) { ... } void dosomething(decimal x) { ... } 

in following method, need call correct overload. how simple implementation like:

void havetodosomething(object data) {     if (data int) dosomething((int)data);     else if (data float) dosomething((float)data);     else if (data decimal) dosomething((decimal)data); } 

this tedious when there ~20 types check. there better way of doing casting automatically?

something forgot mention: dosomething wouldn't work generics, each type needs handled differently, , know type @ runtime.

you can use reflection can have performance impact:

public class example {     void dosomething(int i)     {      }      void dosomething(float i)     {      } }  public static class exampleextensions {     public static void dosomethinggeneric(this example example, object objectparam)     {         var t = objectparam.gettype();         var methods = typeof(example).getmethods().where(_ => _.name == "dosomething");         var methodinfo = methods.single(_ => _.getparameters().first().parametertype == t);         methodinfo.invoke(example, new[] { objectparam });     } } 

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -