Reputation: 24488
I am getting an error when running
string quote = Page.RouteData.Values["quote"].ToString() ?? string.Empty;
Error: Object reference not set to an instance of an object.
I understand that ToString is causing the error since the Page.RouteData.Values["quote"] is empty/null.
How do I check to see if the Page.RouteData.Values["quote"] has a value before we do the ToString?
Upvotes: 2
Views: 6696
Reputation: 1
try this
var quote = Page.RouteData.Values["quote"]?.ToString() ?? string.Empty;
Upvotes: 0
Reputation: 3737
How about:
if (Page.RouteData.Values["quote"] != null) {
string quote = Page.RouteData.Values["quote"].ToString() ?? string.Empty;
}
or
string quote = ((Page.RouteData.Values["quote"] != null) ? Page.RouteData.Values["quote"].ToString() : string.Empty);
Upvotes: 10