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
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:
or using
default
:or provide values of needed types:
Or just use result of the method returning the tuple:
Tuple can have multiple data types and that is what the function returns in your case.
you can create a var
while debugging, you can verify that data is filled properly into the tuple.
or you can create specific type per method return
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.