skip to Main Content

I am fixing a bug on a legacy system. It has a function with return type (string, IDictionary<string, object>). I cannot change the method signature. I want to declare a variable of method return type. I tried this but its giving me an error.

var sqlQuery = new (string, IDictionary<string, object>)

2

Answers


  1. This is a value tuple type (available in C# 7.0 and later) and you can either use target-typed new expression (since C# 9) to fill it with default values:

    (string, IDictionary<string, object>) sqlQuery = new();
    

    or using default:

    (string, IDictionary<string, object>) sqlQuery = default;
    

    or provide values of needed types:

    var sqlQuery = (someString, someDictionary);
    // or
    var sqlQuery = ((string)null, (IDictionary<string, object>)null);
    

    Or just use result of the method returning the tuple:

    var sql = MethodReturningTuple();
    
    Login or Signup to reply.
  2. Tuple can have multiple data types and that is what the function returns in your case.

    you can create a var

     var sqlQuery = method();
    

    while debugging, you can verify that data is filled properly into the tuple.

    or you can create specific type per method return

    (string, IDictionary<string, object>) sqlQuery = method();
    

    It is better to use var as it can change with method signature. Having said that, every pro has cons, code can fail if the type is changed. C# is type safe and (hopefully) compile will detect the type change.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search