Tip
Try also online.
public static TActualValue GetValueOrDefault<TActualValue>(
this IDictionary<string, Object> dictionary,
string key,
TActualValue defaultValue = null
)
<ExtensionAttribute>
Public Shared Function GetValueOrDefault(Of TActualValue) (
dictionary As IDictionary(Of String, Object),
key As String,
Optional defaultValue As TActualValue = Nothing
) As TActualValue
public:
[ExtensionAttribute]
generic<typename TActualValue>
static TActualValue GetValueOrDefault(
IDictionary<String^, Object^>^ dictionary,
String^ key,
TActualValue defaultValue = nullptr
)
[<ExtensionAttribute>]
static member GetValueOrDefault :
dictionary : IDictionary<string, Object> *
key : string *
?defaultValue : 'TActualValue
(* Defaults:
let _defaultValue = defaultArg defaultValue null
*)
-> 'TActualValue
using System;
using System.Collections.Generic;
using KGySoft.CoreLibraries;
public class Example
{
public static void Main()
{
var dict = new Dictionary<string, object>
{
{ "Int", 42 },
{ "String", "Blah" },
};
// old way:
object obj;
int intValue;
if (dict.TryGetValue("Int", out obj) && obj is int)
intValue = (int)obj;
// C# 7.0 way:
if (dict.TryGetValue("Int", out object o) && o is int i)
intValue = i;
// GetValueOrDefault ways:
// TValue return type (which is object now)
intValue = (int)dict.GetValueOrDefault("Int");
// by defining a default value the actual type (and return type) can be specified
intValue = dict.GetValueOrDefault("Int", 0);
// an alternative syntax for string-object dictionaries (a default value still can be specified)
intValue = dict.GetValueOrDefault<int>("Int");
// to use different actual (and return) type for non string-object dictionaries use the GetActualValueOrDefault method:
intValue = dict.GetActualValueOrDefault("Int", 0);
// using nullable int actual type to get null if "Unknown" does not exist or is not an int
int? intOrNull = dict.GetValueOrDefault<int?>("Unknown");
// If obtaining a default value is an expensive operation you can use the delegate overloads.
// The delegate is invoked only when the key was not found in the dictionary:
intValue = (int)dict.GetValueOrDefault("Unknown", () =>
{
Console.WriteLine("Default value factory was invoked from GetValueOrDefault");
return -1;
});
// Which is the same as:
intValue = dict.GetActualValueOrDefault("Unknown", () =>
{
Console.WriteLine("Default value factory was invoked from GetActualValueOrDefault");
return -1;
});
Console.WriteLine($"{nameof(intValue)}: {intValue}; {nameof(intOrNull)}: {intOrNull}");
}
}