Why does Dictionary.ContainsKey throw ArgumentNullException? [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
The documentation states that bool Dictionary<TKey, TValue>.ContainsKey(TKey key) throws an exception in case a null key is passed. Could anyone give a reason for that? Wouldn't it be more practical if it just returned false?

If ContainsKey(null) returned false it would give the misleading impression that null keys are allowed..

This is how it is implemented: (Source)
public bool ContainsKey(TKey key) {
return FindEntry(key) >= 0;
}
And the method FindEntry as:
private int FindEntry(TKey key) {
if( key == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null) {
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i;
}
}
return -1;
}
Since having a null value as key in dictionary is not allowed.
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add(null, 10);
The above would produce an exception:
Value cannot be null. Parameter name: key
For your question:
Wouldn't it be more practical if it just returned false?
Someone from Microsoft could probably reply that. But IMO, since adding a null value for key is not allowed there is no point in checking for null key in ContainsKey

Related

Is there more efficient way to use !=? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Sometimes i need to use != two, three or four times is there a better way to do it?
if (result != 1 && result != 12)
{
do something
}
if (result != 1 && != 12)
{
do something
}
second option would be better, nut we all know it doesn't work
There is not a direct way in the language like the one you suggested:
// Wont compile
if (result != 1 && != 12) { }
If you only have a few values to check, I'd use the explicit comparsions. However you can create a collection of values an check if the result is not in the colleciton:
// using System.Linq;
if (!(new []{ 1, 2 /*, ... */ }).Contains(result)) { }
As suggested in the comments you can also write an extension method. This requires a public static class:
public static class ExtensionMethods
{
public static bool NotIn(this int num, params int[] numbers)
{
return !numbers.Contains(num);
}
}
// usage
result.NotIn(1, 12);
result.NotIn(1, 12, 3, 5, 6);
And if you want to compare not only integers, you can write a generic method:
public static bool NotIn<T>(this T element, params T[] collection)
{
return !collection.Contains(element);
}
// Works with different types
result.NotIn(1, 2, 3, 4);
"a".NotIn("b", "c", "aa");
You can use Linq All() method probably
if((new int[]{1,12,13}).All(x => x != result))
{
// do something
}

Define if statement for property in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
public class hamid
{
private int[] arr = new int[10];
public int[] Arr
{
get => arr;
set
{
if (value < 0)
Environment.Exit(1);
else arr = value;
}
} // If in error.
}
I want have a if statement. For example if (values < 0)
But I have an error, please help me.
value is an array of integer, it can't be zero. Any element in the array could be zero. If you are trying to determine if the array is null, then you could change the check to be:
if (value == null)
{
Environment.Exit(1);
}

Getting the Values from Dictionary [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am going Round-Robin Algorithm. I am doing in that everything must be created dynamically and Randomly. When I want to go second time to check if I have and value the is more than 0 in the checking point it says that "The given key was not present in the dictionary". How can I Fix this problem.
private int GetNextNodeToProcesssRandom()
{
int NextNodeIndex = -1;
if (NextNodeToProcess >= this.waytosave.Count)
{
NextNodeToProcess = 0;
}
for (int i = NextNodeToProcess; i < this.waytosave.Count; i++)
{
if (this.waytosave[i] > 0)//the problem appears here when the cod goes for the second time.
{
NextNodeIndex = i;
break;
}
}
NextNodeToProcess++;
return NextNodeIndex;
}
It is somehow unclear what is your exact goal. However if you want to loop through a Dict you can use:
foreach(KeyValuePair<TKey, TValue> entry in MyDict)
{
// do something with entry.Value or entry.Key
}
Now if you want to add a check in your program you can try:
if (MyDict.ContainsKey(this.waytosave[i]))
///continue execution...
A look here might help you

How do I turn .Any into a for loop? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having some trouble turning the following code into a for loop. The purpose of the code is to check if the string has both a letter and a number in it.
else if (!string.Any(Char.IsLetter) || !string.Any(Char.IsDigit))
{
return false;
}
Any ideas?
Do you mean something like this?
bool anyLetter = false;
bool anyDigit = false;
foreach(var ch in str)
{
if(char.IsLetter(ch)) anyLetter = true;
if(char.IsDigit(ch)) anyDigit = true;
if(anyLetter && anyDigit) break;
}
return anyLetter || anyDigit;
Note that if this string should contain at least one digit and one letter, you need to use && instead of ||
Since Selman22 seems to have already answered the question, another solution I found is I guess you could also use RegEx:
letterCount = Regex.Matches(yourstring,#"[a-zA-Z]").Count;
numberCount = Regex.Matches(yourstring,#"\d").Count;
return letterCount != 0 && numberCount != 0;
Did you mean a loop for a set of strings?
var src = new List<string>{"A4C", "D3F", "G7I"};
var allHaveCharAndDigit = src.TrueForAll(s => s.Any(c => char.IsLetter(c)) && s.Any(c => char.IsDigit(c)));

How to allow average to be null [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
how do i allow this get to be null?
public double? GetSignalAverage
{
get
{
var signalaverage = Gsmdata.Select(x => x.SignalStrength)
.Average();
return Math.Round(signalaverage, 2);
}
}
SignalStrength is an Int
Check if the collection is null or empty:
public double? GetSignalAverage
{
get
{
if(Gsmdata == null || GsmData.Count() == 0)
return null;
var signalaverage = Gsmdata.Select(x => x.SignalStrength)
.Average();
return Math.Round(signalaverage, 2);
}
}
You'll have to declare SignalStrength as int? to allow null values. (If you don't, int will be its default value, which is 0.) But even then, Average() will simply ignore those values, if there is any non-null element (see the documentation).
If they all are null, Average will return null, which you can catch and return, like this:
double? signalaverage = Gsmdata.Select(x => x.SignalStrength)
.Average();
if(signalaverage == null)
{
return signalaverage; // which is essentially 'return null;'
}
else
{
return Math.Round(signalaverage, 2);
}

Categories

Resources