0

I've written a method that executes JavaScript and return value. The returned value could be literately anything. Now I'd like at least to cut the number of repeated code by writing an generic overload.

something like:

public T ExecuteJavascriptWithReturnValue<T>(string js)
{
 object obj = ExecuteJavascriptWithReturnValue(js); --the original method returns an object
 if (typeof(T) == typeof(int) || typeof(T) == typeof(double) ||typeof(T) == typeof(string))
      return (T)(obj);
}
else
{
   throw new Exception("For objects other than int, float, double, or string, please use the non generic version.");
}

I'm getting the the following error: specified cast is not valid. The only time this code works is when the object returned is of type string.

Thanks for helping.

EDIT

public object ExecuteJavascriptWithReturnValue(string js)
{
   IJavaScriptExecutor jse = driver as IJavaScriptExecutor;
   object result = jse.ExecuteScript(js);
   return result;
}

This method can return litteraly anything, for instance, a collections, a string, a number, etc. Here's the metadata:

...object ExecuteScript(string script, params object[] args);

and a script could be something like:

string js = "return $('#calculateValueStep > span.k-widget.k-numerictextbox > span >"
          + " input.k-formatted-value.k-input').val();";

I use this method often. So, I want a generic method for those time I'm expecting an object of type, such as int, double, and son forth.

Richard77
  • 20,343
  • 46
  • 150
  • 252

1 Answers1

2

Maybe try this:

 return (T)Convert.ChangeType(obj, typeof(T));
Festyk
  • 316
  • 1
  • 6