c# hashtable get value by key

There are few possibilities:

you have already inserted null under the mykey before and now you are getting it back since if statement returns true
myval is null and your code works flawlessly
mykey is of type which has a very strange implementation of GetHashCode
The first 2 options are not actually possible, as hashtbl[mykey].ToString() would throw NullObjectReference. I would also assume that this is not the real code as I can't think of a scenario where x.ToString() would return null, unless you forgot to mention that myval is of your custom type which overrides it in a strange way.

Therefore, I would assume the latter: myval is your type which overrides ToString in a way that it returns null.

EDIT: after showing your code and clarifying that the last line doesn't return null but instead throws, it looks like the second scenario is happening. If you run your code through debugger, you will see that you are inserting null values for each entry where key index is > 2. Therefore, hashtable returns null.

This snippet is suspicious: ValueArray.GetUpperBound(0) - 1. Try removing '-1'.

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source