I have a condition where I am creating a payload with key value pair and depending of a condition the value will change. How can I achieve this without using dynamic
as my data type?
dynamic finalList;
if(condition)
finalList = new List<object>() {...};
else
finalList = object.ExistingList;
I am consuming this finalList as a value in payload.
Placeholders = new Dictionary<string, object> {
{ "keyForList", finalList }
}
Is there any other way I can achieve above logic without using dynamic as my datatype for finalList
as I don't know future challenges I might face for using it. Also, finalList
might go under some further computation in future.
CodePudding user response:
Your dictionary is defined as Dictionary<string, object>
. Use an object
type instead of dynamic
:
object finalList = condition
? new List<object>() {...}
: object.ExistingList;
However, I suspect the object.ExistingList
is an IEnumerable
. If so, then use the common interface for both lists:
IEnumerable<object> finalList = condition
? new List<object>() {...}
: object.ExistingList;