Need an IDictionary<TKey,TValue> implementation that will allow a null key - c#

Basically, I want something like this:
Dictionary<object, string> dict = new Dictionary<object, string>();
dict.Add(null, "Nothing");
dict.Add(1, "One");
Are there any built into the base class library that allow this? The preceding code will throw an exception at runtime when adding the null key.

You could avoid using null and create a special singleton value class that does the same thing. For example:
public sealed class Nothing
{
public static readonly Nothing Value = new Nothing();
private Nothing() {}
}
Dictionary<object, string> dict = new Dictionary<object, string>();
dict.add(Nothing.Value, "Nothing");
dict.add(1, "One");
This approach will fail to work if you intend to make your collection more strongly typed - let's say for example you want the key to be a string. Since string is sealed you can't inherit from it to create a "special value" substitute for null. Your alternatives become a bit more complicated. You could:
Create some special constant value to represent the "empty" / "null" case. Kind of hacky and definitely a path to confusion. This can be a viable approach if the dictionary is completely private to some implementation class and you can write some Encode/Decode utility methods to avoid spreading the knowledge of how you translate keys all over the place.
Create your own implementation of IDictionary that internally delegates to a Dictionary<> instance - except for the case of null. This violates the documented expectations for the IDictionary<> interface which does say that null keys should throw an exception. But you may be able to get away with it if it's the only way to solve your real problem. This only works if you own and create the dictionary instance.
Find a way to solve your problem without storing a "null" key in the dictionary. For example, consider not populating the null key in the dictionary and having some special case logic to deal with it. Keys have to be hashable and comparable to work with the underlying implementation, which is why null is prohibited normally.
As an aside, does your dictionary key really need the key to be object? This can lead to subtle bugs due to reference equality being used where you may have intended Equals() to be evaluated as the basis for comparison.

How about this?
public class NullableDictionnary<T1, T2> : Dictionary<T1, T2>
{
T2 null_value;
public T2 this[T1 key]
{
get
{
if (key == null)
{ return null_value; }
return base[key];
}
set
{
if (key == null)
{ null_value = value; }
else
{ base[key] = value; }
}
}
}

NameValueCollection can take a null key but it does not implement IDictionary. It would however be pretty easy to derive from DictionaryBase and provide Add/Remove/Indexers etc that simply replace null with something built in like:
class MyDictionary : DictionaryBase {
private readonly object nullKey = new object();
void Add(object key, string value) {
if ( key == null ) { key = nullKey; }
.. call base methods
}
}

You can simply use ValueTuple as a wrapper for key, for example:
Dictionary<ValueTuple<string?>, string>

No need for a different implementation of Dictionary.
Take a look at my answer here:
https://stackoverflow.com/a/22261282/212272
You will also be able to keep your dictionary strongly typed:
var dict = new Dictionary<NullObject<int?>, string>();
dict[1] = "one int";
dict[null] = "null int";
Assert.AreEqual("one int", dict[1]);
Assert.AreEqual("null int", dict[null]);

If key is enum, you can use not existing value instead of null like (YourEnum)(-1)

Does the key literally need to be NULL? The key in the collection works out to be an index. It doesn't make a lot of sense to me to have NULL for an index in a collection.
Maybe create a new class
public class ObjectEntry
{
public object objRef;
public string desc;
public ObjectEntry(object objectReference)
{
objRef = objectReference;
if (objRef = null) {desc = "Nothing";}
else {desc = objRef.Description;} //or whatever info you can get from a proper objRef value
}
}
newObj = new ObjectEntry(null);
dict.add(newObj, newObj.desc);

A slight variation on jestro's answer to make for a cleaner(to me) solution that makes it more explicit what you are trying to do. Obviously this could be extended as needed. But you get the picture, just make a wrapper.
public class NullDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
private TValue _default;
public new TValue this[TKey key]
{
get {
if(key == null)
{
return _default;
}
return _decorated[key];
}
}
private Dictionary<TKey, TValue> _decorated;
public NullDictionary( Dictionary<TKey,TValue> decorate, TValue defaultValue = default)
{
_decorated = decorate;
_default = defaultValue;
}
}

Related

Convenience method to find or add value to generic dictionary

Many times over the years, I have needed code that does:
Find a value in a dictionary; if it is not there, add it to the dictionary (and return that new value).
For example:
// Only one per account, so loading can be efficiently managed.
// <AccountID, LCProfilePicture>
public readonly static Dictionary<int, LCProfilePicture> All = new Dictionary<int, LCProfilePicture>();
public static LCProfilePicture GetOrCreate( int accountID )
{
LCProfilePicture pic;
if (!All.TryGetValue( accountID, out pic )) {
pic = new LCProfilePicture( accountID );
All[ accountID ] = pic;
}
return pic;
}
Instead of having to write that boilerplate each time, I'd like to have a generic method that will do the work. How to do so in c#?
So far, I have thought of three ways to proceed:
Wrap the construction that will be needed if the dictionary does not already contain an object for the key, into an Action (or Func?). Then call that if necessary.
Require TValue to have a constructor of that form, and then somehow describe that requirement as a constraint on the generic method.
Define some interface that TValue has to satisfy, and somehow use that interface to write the generic method.
I think I know how to do #1, so will submit an answer doing so, as soon as I work out the details. UPDATE: I have now worked that out, and posted that as an answer.
But maybe #2 is possible? Then I could just add that constraint, and be done.
Pro: easier to use (don't have to wrap the construction into an Action or Func).
Con: Not as flexible (if have a TValue that does not have such a constructor, can't use this generic method).
(#3 seems less promising; I mention it for completeness.)
You can combine constraints of new() and an interface for setting the key, like this:
interface IWithKey<T> {
public T Key { get; set; }
}
static class DictExtensions {
public static TVal GetorCreate<TKey,TVal>(this IDictionary<TKey,TVal> d, TKey key) where TVal : new(), IWithKey<TKey> {
TVal res;
if (!d.TryGetValue(key, out res)) {
res = new TVal();
res.Key = key;
d.Add(key, res);
}
return res;
}
}
Since GetorCreate is an extension, you can use it as follows:
static LCProfilePicture GetOrCreatePic( int accountID ) {
return All.GetOrCreateEntry(accountID);
}
I noticed in your example you have a static dictionary
// Only one per account, so loading can be efficiently managed.
// <AccountID, LCProfilePicture>
public readonly static Dictionary<int, LCProfilePicture> All =
new Dictionary<int, LCProfilePicture>();
My first reaction to that is, since it is static, are you going to need it to be thread safe. If the answer is yes, maybe, or even no, then the answer might be, don't write it yourself, let Microsoft do it.
System.Collections.Concurrent.ConcurrentDictionary<TKey, TValue>
Which so happens to have 2 built in functions
TValue GetOrAdd(TKey key, TValue value)
TValue GetOrAdd(TKey key, Func<TKey, TValue> func)
And all of that done in a thread-safe manner.
The second one where the parameter is a Func is the maybe the answer you are looking for.
If you are set on simplifying the usage, I would argue against having the loading of the data be part of the TValue. That is mostly based on my own person preference to store POCO (Plain Old CLR Objects) as values is Dictionaries and not objects with State and Behavior.
I would instead, move the "loading/constructing/deserializing" behavior to another service and/or the Dictionary itself.
This example creates a base class that you inherit from
public abstract class SmartConcurrentDictionaryBase<TKey, TValue> :
System.Collections.Concurrent.ConcurrentDictionary<TKey, TValue>
{
public TValue GetOrAdd(TKey key) { return GetOrAdd(key, LoadNewValue); }
protected abstract TValue LoadNewValue(TKey key);
}
public class LCProfilePictureDictionary : SmartConcurrentDictionaryBase<int, LCProfilePicture>
{
protected override LCProfilePicture(int accountID)
{
return new LCProfilePicture(accountID);
}
}
// use is
// var pic = All.GetOrAdd(accountID);
This example is more of a reusable Dictionary object and takes in a Func as a constructor parameter, but could easily be changed to include an Interface where one of the functions on the interface match the pattern.
public class SimpleConcurrentDictionary<TKey, TValue> :
System.Collections.Concurrent.ConcurrentDictionary<TKey, TValue>
{
private readonly Func<TKey, TValue> _loadFunc;
public SimpleConcurrentDictionary(Func<TKey, TValue> loadFunc)
{
_loadFunc = loadFunc;
}
public TValue GetOrAdd(TKey key) { return GetOrAdd(key, _loadFunc); }
}
System.Reflection has a ConstructorInfo object and a GetConstructor method that can be used for this purpose. ConstructorInfo.Invoke returns an object of the type that you used to create your ConstructorInfo. If you went the reflection route, it would look something like this (not tested, but should be close):
//using System.Reflection;
public static TValue GetOrCreateEntry<TKey, TValue>(Dictionary<TKey, TValue> dict, TKey key)
{
TValue value;
if (!dict.TryGetValue(key, out value))
{
// not in dictionary
ConstructorInfo ctor = typeof(TValue).GetConstructor(new Type[] { typeof(TKey) });
if (ctor != null)
{
// we have a constructor that matches the type you need
value = (TValue)ctor.Invoke(new object[] { key });
dict[key] = value;
return value;
}
else
throw new NotImplementedException(); // because the TValue type does not implement the constructor you anticipate
}
// we got it from dictionary, so just return it
return value;
}
Solution #1 (most general):
public static TValue GetOrCreateEntry<TKey, TValue>( Dictionary<TKey, TValue> dict, TKey key, Func<TValue> creator )
{
TValue value;
if (!dict.TryGetValue( key, out value )) {
value = creator();
dict[ key ] = value;
}
return value;
}
Example usage:
static LCProfilePicture GetOrCreatePic( int accountID )
{
return GetOrCreateEntry<int, LCProfilePicture>( All, accountID, () => new LCProfilePicture( accountID ) );
}
Solution #2 (for TValues that remember their key):
public static TValue GetOrCreateEntry<TKey, TValue>( Dictionary<TKey, TValue> dict, TKey key, Func<TKey, TValue> creator )
{
TValue value;
if (!dict.TryGetValue( key, out value )) {
value = creator(key);
dict[ key ] = value;
}
return value;
}
Example usage:
static LCProfilePicture GetOrCreatePic( int accountID )
{
return GetOrCreateEntry<int, LCProfilePicture>( All, accountID, key => new LCProfilePicture( key ) );
}
Comparison of Solution #1 and Solution 2:
Solution #1 is more general - it can be used even for TValues that don't need to know about the key.
Solution #2 is cleaner style, for TValues that do retain a reference to the key.
Two reasons #2 is preferable, where appropriate:
Reason #1: Solution #1 has the possibility of abuse: consider the case where TValue has two constructors, a parameterless one, and one that takes key as a parameter. An inexperienced programmer might use Solution #1 like this:
static LCProfilePicture GetOrCreatePic( int accountID )
{
// OOPS, programmer has not set the key field to "accountID".
return GetOrCreateEntry<int, LCProfilePicture>( All, accountID, () => new LCProfilePicture() );
}
If the lead programmer / architect wants to avoid that possibility, omit Solution #1, and only offer #2. In that case, the attempted usage won't compile, because there is no matching constructor.
Reason #2: Using Solution #1 requires including a second copy of the key in the usage, if TValue needs to capture it. This unnecessarily encapsulates the key in the Func instance, and could lead to accidentally referring to a different key, e.g.:
//...
int keyA;
int keyB;
// OOPS, programmer referred to the wrong key the second time.
// Maybe copy/pasted code, and only changed it in the first location, not realizing it is used in two places.
var valA = GetOrCreateEntry<int, LCProfilePicture>( All, keyA, () => new LCProfilePicture( keyB) );
enter code here

Class design for read-only collection properties

I have an IDictionary<string, MyEnum?> collection that needs to be passed to a class to wrap it in a IReadOnlyDictionary<string, MyEnum> (note MyEnum but not MyEnum?).
I have come up with two designs:
Delay the wrapping to IReadOnlyDictionary<string, MyEnum> until property access:
public class MyClass
{
private readonly IEnumerable<KeyValuePair<string, MyEnum?>> _kvps;
public MyClass(IEnumerable<KeyValuePair<string, MyEnum?>> kvps)
{
_kvps = kvps;
}
public IReadOnlyDictionary<string, MyEnum> Kvps
{
get
{
var filtered = from kvp in _kvps
where kvp.Value.HasValue
select kvp;
return new ReadOnlyDictionary<string, MyEnum>(
filtered.ToDictionary(kvp => kvp.Key, kvp => (MyEnum)kvp.Value);
}
}
}
Eagerly evaluate the collection in constructor
public class MyClass
{
public MyClass(IEnumerable<KeyValuePair<string, MyEnum?>> kvps)
{
Kvps = ToReadOnly(kvps);
}
public IReadOnlyDictionary<string, MyEnum> Kvps { get; }
private static IReadOnlyDictionary<string, MyEnum> ToReadOnly(
IEnumerable<KeyValuePair<string, MyEnum?>> kvps)
{
var filtered = from kvp in kvps
where kvp.Value.HasValue
select kvp;
return new ReadOnlyDictionary<string, MyEnum>(
filtered.ToDictionary(kvp => kvp.Key, kvp => (MyEnum)kvp.Value);
}
}
The constructor design section of the Framework Design Guidelines suggests that minimal work should be done in constructors so I am opting for the first approach. However, that means every call to MyClass.Kvps will trigger a copy of _kvps which is not ideal.
I would like to know which is a better approach (or are there other ways) in terms of:
Memory efficiency (ideally only one copy of the collection is stored in MyClass)
Performance (property access should be fast and should not trigger a copy of the KeyValuePairs)
Out of the two requirements - don't copy the key value pairs and don't store two copies - you'll have to break one.
What causes us to look at this and think that there must be a solution is that we see TValue and TValue? and our minds want to see them as being of the same type. But they are not the same type.
It becomes clearer if you imagine that instead of TValue and TValue? that these are two different types, like an int and a string, and we want to project a collection of one to a collection of the other while filtering. For example,
List<string> GetStringsFromNonNegativeInts(List<int> ints)
{
return ints.Where(i=>i>-1).Select(i=>i.ToString()).ToList();
}
That's exactly the same scenario as trying to filter a set of TValue? to a set of TValue, even without the dictionary. It's just harder to see. TValue and TValue? code-blind us.
There are only two ways to do this. One is to copy each time, and the other is to keep two lists in synchronization.
EDIT: If you want the latest source values, best way is to implement your own class that implements IReadOnlyDictionary. Initialize this with a private field of ReadOnlyDictionary<string, MyEnum?>. Each call will do the lookup, and if the key exists AND HasValue, return the value.
Note that this implementation depends on the reference to the original values being passed in as an IReadOnlyDictionary to avoid having to copy values over.
public class MyReadOnlyDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue> where TValue : struct
{
// other methods to implement here...
public MyReadOnlyDictionary(IReadOnlyDictionary<TKey, TValue?> kvps)
{
_kvps = kvps;
}
private IReadOnlyDictionary<TKey, TValue?> _kvps;
new public TValue this[TKey key]
{
get
{
TValue? val = _kvps[key];
if (val.HasValue)
return val.Value;
throw new KeyNotFoundException();
}
}
}

How to get null instead of the KeyNotFoundException accessing Dictionary value by key? [duplicate]

This question already has answers here:
Is there an IDictionary implementation that, on missing key, returns the default value instead of throwing?
(17 answers)
Closed 5 years ago.
In some certain scenario it appeared to be useful for me to have a short-spoken, readable way to get null instead of the KeyNotFoundException while accessing dictionary value by key, when there is no such key in the dictionary.
The first thing that came into my mind was an extension method:
public static U GetValueByKeyOrNull<T, U>(this Dictionary<T, U> dict, T key)
where U : class //it's acceptable for me to have this constraint
{
if (dict.ContainsKey(key))
return dict[key];
else
//it could be default(U) to use without U class constraint
//however, I didn't need this.
return null;
}
But it's not very short-spoken actually, when you write something like this:
string.Format("{0}:{1};{2}:{3}",
dict.GetValueByKeyOrNull("key1"),
dict.GetValueByKeyOrNull("key2"),
dict.GetValueByKeyOrNull("key3"),
dict.GetValueByKeyOrNull("key4"));
I'd say, it would be much better to havesomething close to base syntax: dict["key4"].
Then I came up with an idea to have a class with a private dictionary field, which exposed the functionality I need:
public class MyDictionary<T, U> //here I may add any of interfaces, implemented
//by dictionary itself to get an opportunity to,
//say, use foreach, etc. and implement them
// using the dictionary field.
where U : class
{
private Dictionary<T, U> dict;
public MyDictionary()
{
dict = new Dictionary<T, U>();
}
public U this[T key]
{
get
{
if (dict.ContainsKey(key))
return dict[key];
else
return null;
}
set
{
dict[key] = value;
}
}
}
But it seems a little overhead to get the slight change in the basic behaviour.
One more workaround could be to define a Func in the current context like this:
Func<string, string> GetDictValueByKeyOrNull = (key) =>
{
if (dict.ContainsKey(key))
return dict[key];
else
return null;
};
so it could be utilized like GetDictValueByKeyOrNull("key1").
Could you, please, give me any more suggestions or help to choose a better one?
Here is my solution from my personal library, implemented as an extension method. I am only posting it because it is implemented from the dictionary interface and allows an optional default value to be passed in.
Implementation
public static TV GetValue<TK, TV>(this IDictionary<TK, TV> dict, TK key, TV defaultValue = default(TV))
{
TV value;
return dict.TryGetValue(key, out value) ? value : defaultValue;
}
Usage
MyDictionary.GetValue("key1");
MyDictionary.GetValue("key2", -1);
MyDictionary.GetValue("key3")?.SomeMethod();
You can't get the syntax you want with an extension method, and as others have said overriding a method/operator to change its behavior is generally not a great idea. I think the best you can do is shorten the name you use.
That's if you need to keep to the IDictionary interface. If you aren't interfacing with any code that expects an IDictionary, then you are free to define your own interface and having the [] operator work differently isn't a problem.
Whatever you end up calling the function, you'll want to implement it like this:
public static U Get<T, U>(this Dictionary<T, U> dict, T key)
where U : class
{
U val;
dict.TryGetValue(key, out val);
return val;
}
It just does one lookup, compared with 2 for your implementations.
In the end I came up with a variant using a deriving from dictionary class with explicit interface implementation:
public interface INullValueDictionary<T, U>
where U : class
{
U this[T key] { get; }
}
public class NullValueDictionary<T, U> : Dictionary<T, U>, INullValueDictionary<T, U>
where U : class
{
U INullValueDictionary<T, U>.this[T key]
{
get
{
U val;
this.TryGetValue(key, out val);
return val;
}
}
}
So it exposes the functionality I need the following way:
//create some dictionary
NullValueDictionary<int, string> dict = new NullValueDictionary<int, string>
{
{1,"one"}
};
//have a reference to the interface
INullValueDictionary<int, string> idict = dict;
try
{
//this throws an exception, as the base class implementation is utilized
Console.WriteLine(dict[2] ?? "null");
}
catch { }
//this prints null, as the explicit interface implementation
//in the derived class is used
Console.WriteLine(idict[2] ?? "null");
Add a DictionaryExtension class
public static class DictionaryExtension
{
public static TValue GetValueOrDefault<TKey, TValue>
( this IDictionary<TKey, TValue> dictionary,TKey key)
{
TValue value;
return dictionary.TryGetValue(key, out value) ? value : default(TValue);
}
}
And it can return Default value if not found key in dictionary.
The Default is null if this is reference type .
_dic.GetValueOrDefault();
Worth pointing out that the HybridDictionary does this by default.
You lose the generic typeing, but get the null-if-not-found functionality.
And (at least theoretically) you get performance benefits at low numbers of values, I think.
I premise by saying that I would not use this. The new keyword, while useful in this case, can create bugs which are really hard to find. Other than that, you can try this class.
class MyDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public new TValue this[TKey key]
{
get
{
TValue value;
return TryGetValue(key, out value) ? value : default(TValue);
}
set { base[key] = value; }
}
}
I've done this before and it worked pretty well to just inherit the regular Dictionary class and just hide the indexer. It's really clean to do it this way so you automatically acquire all the reliability and familiarity of the Regular Dictionary class.
public class NullSafeDict<TKey, TValue> : Dictionary<TKey, TValue> where TValue : class
{
public new TValue this[TKey key]
{
get
{
if (!ContainsKey(key))
return null;
else
return base[key];
}
set
{
if (!ContainsKey(key))
Add(key, value);
else
base[key] = value;
}
}
}

"Verbose Dictionary" in C#, 'override new' this[] or implement IDictionary

All I want is a dictionary which tells me which key it couldn't find, rather than just saying The given key was not present in the dictionary.
I briefly considered doing a subclass with override new this[TKey key], but felt it was a bit hacky, so I've gone with implementing the IDictionary interface, and passing everything through directly to an inner Dictionary, with the only additional logic being in the indexer:
public TValue this[TKey key]
{
get
{
ThrowIfKeyNotFound(key);
return _dic[key];
}
set
{
ThrowIfKeyNotFound(key);
_dic[key] = value;
}
}
private void ThrowIfKeyNotFound(TKey key)
{
if(!_dic.ContainsKey(key))
throw new ArgumentOutOfRangeException("Can't find key [" + key + "] in dictionary");
}
Is this the right/only way to go? Would newing over the this[] really be that bad?
Sounds like a good fit for an extension method:
public static class SomeUtilClass {
public static TValue VerboseGetValue<TKey, TValue>(
this IDictionary<TKey, TValue> data, TKey key)
{
TValue result;
if (!data.TryGetValue(key, out result)) {
throw new KeyNotFoundException(
"Key not found: " + Convert.ToString(key));
}
return result;
}
}
This will then work on all your existing dictionaries whenever you call VerboseGetValue, for example:
var data = new Dictionary<int, string> { { 123, "abc" } };
Console.WriteLine(data.VerboseGetValue(123));
Console.WriteLine(data.VerboseGetValue(456));
Instead of doing ContainsKey and checking for the presence of the key before touching the underlying dictionary, why not do
get {
try {
return _dic[key];
}
catch (ArgumentOutOfRangeException) {
throw new ArgumentOutOfRangeException(......);
}
}
That way, you only pay for the extra checking in the failure case - the success case, which is hopefully more common, doesn't have to do an extra dictionary lookup. This is good for get, but set is more difficult since the default behaviour of set is to always work. If you don't want that then you would need to check for the existence of the key first.
If you want to do this, you are going to have to roll your own in one way or another. But I'm going to question WHY you would want to do this?

What happens to C# Dictionary<int, int> lookup if the key does not exist?

I tried checking for null but the compiler warns that this condition will never occur. What should I be looking for?
Assuming you want to get the value if the key does exist, use Dictionary<TKey, TValue>.TryGetValue:
int value;
if (dictionary.TryGetValue(key, out value))
{
// Key was in dictionary; "value" contains corresponding value
}
else
{
// Key wasn't in dictionary; "value" is now 0
}
(Using ContainsKey and then the indexer makes it look the key up twice, which is pretty pointless.)
Note that even if you were using reference types, checking for null wouldn't work - the indexer for Dictionary<,> will throw an exception if you request a missing key, rather than returning null. (This is a big difference between Dictionary<,> and Hashtable.)
The Dictionary throws a KeyNotFound exception in the event that the dictionary does not contain your key.
As suggested, ContainsKey is the appropriate precaution. TryGetValue is also effective.
This allows the dictionary to store a value of null more effectively. Without it behaving this way, checking for a null result from the [] operator would indicate either a null value OR the non-existance of the input key which is no good.
If you're just checking before trying to add a new value, use the ContainsKey method:
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
}
If you're checking that the value exists, use the TryGetValue method as described in Jon Skeet's answer.
You should check for Dictionary.ContainsKey(int key) before trying to pull out the value.
Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(2,4);
myDictionary.Add(3,5);
int keyToFind = 7;
if(myDictionary.ContainsKey(keyToFind))
{
myValueLookup = myDictionay[keyToFind];
// do work...
}
else
{
// the key doesn't exist.
}
A helper class is handy:
public static class DictionaryHelper
{
public static TVal Get<TKey, TVal>(this Dictionary<TKey, TVal> dictionary, TKey key, TVal defaultVal = default(TVal))
{
TVal val;
if( dictionary.TryGetValue(key, out val) )
{
return val;
}
return defaultVal;
}
}
Consider the option of encapsulating this particular dictionary and provide a method to return the value for that key:
public static class NumbersAdapter
{
private static readonly Dictionary<string, string> Mapping = new Dictionary<string, string>
{
["1"] = "One",
["2"] = "Two",
["3"] = "Three"
};
public static string GetValue(string key)
{
return Mapping.ContainsKey(key) ? Mapping[key] : key;
}
}
Then you can manage the behaviour of this dictionary.
For example here: if the dictionary doesn't have the key, it returns key that you pass by parameter.
ContainsKey is what you're looking for.
You should probably use:
if(myDictionary.ContainsKey(someInt))
{
// do something
}
The reason why you can't check for null is that the key here is a value type.
int result= YourDictionaryName.TryGetValue(key, out int value) ? YourDictionaryName[key] : 0;
If the key is present in the dictionary, it returns the value of the key otherwise it returns 0.
Hope, this code helps you.

Categories