Ravi Ram
Ravi Ram

Reputation: 24488

Check if Page.RouteData.Values has a value

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

Answers (2)

Joost
Joost

Reputation: 1

try this

var quote = Page.RouteData.Values["quote"]?.ToString() ?? string.Empty;

Upvotes: 0

poplitea
poplitea

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

Related Questions