Reputation: 39484
I have the following property:
IDictionary<string, object> Values { get; }
The property has a few values having one of them the key "culture".
I tried to use that value and casting to a string:
String value = (String)data.Values["culture"] ?? defaultCulture;
This works when the item has some value but when it doesn't I get the error:
Unable to cast object of type 'System.Web.Mvc.UrlParameter' to type 'System.String'.
BTW, System.Web.Mvc.UrlParameter: http://msdn.microsoft.com/en-us/library/system.web.mvc.urlparameter%28v=vs.108%29.aspx
In the debugger data.Values["culture"] has the value {}. I tested and:
var test_1 = data.Values["culture"] == null; // returns false
var test_2 = data.Values["culture"].ToString() == null; // returns false
How do I check if data.Values["culture"] has something in it or not?
Upvotes: 0
Views: 184
Reputation: 244998
If you want to get the string
if it indeed is a string and a default value otherwise, you can test the type of the valuer using as
. Something like:
(data.Values["culture"] as string) ?? defaultCulture
Upvotes: 1
Reputation: 10014
Try this:
String value = (String) (data.Values["culture"] ?? defaultCulture);
The idea is to check for null before trying to cast.
Upvotes: 0
Reputation: 161831
Apparently, you are storing a UrlParameter
in that dictionary entry. If you want to get a string out, you will need to use ToString()
.
The exact expression to use will depend on the type of defaultCulture
. If it is a string, then
String value = data.Values["culture"] == null ? defaultCulture : data.Values["culture"].ToString();
if it is a UrlParameter, then
String value = (data.Values["culture"] ?? defaultCulture).ToString();
Upvotes: 3