-2

I have the following code where className is the string value that I need to pass as a class so that I can avoid writing multiple switch-case statements.

 [When(@"Execute Request with model ""(.*)""")]
        public void WhenExecuteRequestWithModel(string className)
        {
            switch (className)
            {
                case "Customer":
                    if (_settings.Request.Method == Method.GET)
                        _settings.Response = _settings.RestClient.Execute<Customer>(_settings.Request);
                    else
                        _settings.Response = _settings.RestClient.ExecuteAsyncRequest<Customer>(_settings.Request).GetAwaiter().GetResult();
                    break;
                case "CustomerStatus":
                    if (_settings.Request.Method == Method.GET)
                        _settings.Response = _settings.RestClient.Execute<CustomerStatus>(_settings.Request);
                    else
                        _settings.Response = _settings.RestClient.ExecuteAsyncRequest<CustomerStatus>(_settings.Request).GetAwaiter().GetResult();
                    break;
            }
        }

Please help

naanku
  • 1
  • 1
  • 2
    "Please help" with what? If you want to use reflection to call your methods look [here](https://stackoverflow.com/questions/232535). A cleaner fix would be to make this function generic but it sounds like the attribute is auto-wiring it to something. – D Stanley Dec 18 '19 at 15:59

1 Answers1

3

It looks like you're trying to bind this with Specflow, and so you can only pass in a string. If the passed className were the full name of the class, or if you are able to deduce the class's full name (by prepending a namespace, for example) then you should be able to use Reflection to instantiate the appropriate generic method.

But, frankly, you might be better off just sticking with a switch statement. Either way, you should be able to reduce repetitive code by creating a helper method.

        switch (className)
        {
            case "Customer":
                ExecuteRestMethod<Customer>()
                break;
            case "CustomerStatus":
                ExecuteRestMethod<CustomerStatus>();
                break;
        }

public void ExecuteRestMethod<T>()
{
                if (_settings.Request.Method == Method.GET)
                    _settings.Response = _settings.RestClient.Execute<T>(_settings.Request);
                else
                    _settings.Response = _settings.RestClient.ExecuteAsyncRequest<T>(_settings.Request).GetAwaiter().GetResult();
}
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315