Home > Back-end >  Adding dictionary security inside a generalized function (.Net Framework 4.8)
Adding dictionary security inside a generalized function (.Net Framework 4.8)

Time:12-31

I have this function call

FunctionName( List, s => new Class(s,Dictionary[s.Key]));

Inside the FunctionName

private void FunctionName<T>(List<T> Data, Func<KeyValuePair<string, object>,T>)
        {
              foreach (... entry in ...)
              {
                  Data.Add(ClassCreator(entry));
              }
            
            return;
        }

The problem is, because FunctionName is generic i cannot add a dictionary checking in case of KeyNotFoundException because it could be other type of variable all along.

Is it possible to add that verification in the function calling?

Something like:

if(KeyNotFoundException) {string.Empty}
else{Dictionary[...]}

Answer

FunctionName(
List, 
object value;
if (Dictionary.TryGetValue(s.Key, out value)) {
     FunctionName(s => new Class(s, value)); 
} 
else {     
     FunctionName(s => new Class(s, string.Empty)); }
);

CodePudding user response:

You could do the checking in the lambda:

F(s => new Class(s, dict.TryGetValue(s.Key, out var x) ? x : string.Empty));
  •  Tags:  
  • c#
  • Related