Flood Gravemind
Flood Gravemind

Reputation: 3803

How to propogate null instance in C#/MVC without If/Else or Try/Catch?

I have an entry in Razor View which is

<li data-img-url="@stock["images"][0]["url"]">
@* stock is a JObject which can contain or cannot contain ["images"]*@

Irrespective of location of null occurence, how to get the final string data-img-url="". Also how to handle such situations where output of statement is needed without adding extra code blocks such as If/Else or Try/Catch

Upvotes: 0

Views: 83

Answers (4)

Ashmosis
Ashmosis

Reputation: 1

Use a ternary:

<li data-img-url="@(stock["images"][0]["url"]! = null:stock["images"][0]["url"]:"""> @* stock is a JObject which can contain or cannot contain ["images"]*@

If the doesn't work, encase the entire attribute in the ternary.

Upvotes: 0

Vishal Sharma
Vishal Sharma

Reputation: 2803

JObject has a SelectToken method which you can utilize for your scenario.

  JObject jsonDoc = JObject.Parse(json);

  Console.WriteLine(jsonDoc.SelectToken("images[0].url"));

Here you will find reference code for SelectToken

SelectToken will return empty if no token found and return results if its a valid result

Upvotes: 2

Ahmed Msaouri
Ahmed Msaouri

Reputation: 316

I do not know if I have understood the question well, but according to what you want to do you have to put an if:

@(stock["images"][0]["url"] == null ? "" : stock["images"][0]["url"])

it is an if, but with linear syntax

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063328

In just C#, the null-propagating operator can help here, i.e.

var x = obj?["bar"];

note however that this only deals with nulls; it won't help you if the problem is a KeyNotFoundException (because obj isn't null, but there's no key "bar"). So: in the general case: just write a method that does what you need, and which also makes everything cleaner; this could be an extension method on whatever stock is, noting that extension methods do not null check on the this argument:

public static string GetFrob(this Stock stock, string grapple, int foo, string blap)
{...}

...

<li data-img-url="@stock.GetFrob("images", 0, "url")">

Upvotes: 1

Related Questions