Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC/C#: Can I avoid repeating myself in a one-line C# conditional statement?

Tags:

c#

asp.net-mvc

Consider the following code that I'm using when displaying a Customer's mailing address inside a table in a view:

<%: Customer.MailingAddress == null ? "" : Customer.MailingAddress.City %>

I find myself using a fair amount of these ternary conditional statements and I am wondering if there is a way to refer back to the object being evaluated in the condition so that I can use it in the expression. Something like this, perhaps:

<%: Customer.MailingAddress == null ? "" : {0}.City %>

Does something like this exist? I know I can create a variable to hold the value but it would be nice to keep everything inside one tight little statement in the view pages.

Thanks!

like image 564
Jeff Camera Avatar asked Oct 28 '10 20:10

Jeff Camera


People also ask

What is MVC in .NET C#?

Model View Controller (MVC) MVC is a design pattern used to decouple user-interface (view), data (model), and application logic (controller). This pattern helps to achieve separation of concerns.

Is ASP.NET MVC outdated?

Note that the entire ASP.NET MVC library is now obsolete.

What is difference between C# and ASP.NET MVC?

They are the same thing. C# is the language you have used to do your development, but ASP.NET MVC is the framework you used to do it.

Is ASP.NET MVC easy to learn?

It's really difficult to try and learn an entirely new language/framework under pressure. If you're required to deliver working software for your day job, trying to learn ASP.NET Core at the same time might be heaping too much pressure on yourself.


1 Answers

No, there is not a way to do precisely what you're asking without creating a variable or duplicating yourself, though you can do something like this:

(Customer.MailingAddress ?? new MailingAddress()).City ?? string.Empty

This presumes that a new MailingAddress will have it's city property / field null by default.

The last null coalescence can be removed if creating a new MailingAddress initializes the city field / property to empty string.

But this isn't actually shorter, and it's more hackish (in my opinion), and almost certainly less performant.

like image 173
McKay Avatar answered Oct 20 '22 04:10

McKay