What is the general way to output non-empty or default return values (Type)
Working with all dictionaries in ASP.NET MVC (like RouteData, DataTokens, etc.), I often find I want to do things like:
bool isLolCat = routeData["isLolcat"] as bool
which will return the casted value or the default (false in this case) when the value is null.
Is there some short, readable, easy way to do this, or would I be better off writing a helper extension method?
The extension method will be something like this.
bool isLolCat = routeData["isLolcat"].TryCast<bool>();
- I prefer not to reinvent the wheel with special syntax if there is a general way to do it.
- I don't want to clutter my code with multiple lines when I am just trying to get a bool from a dictionary.
source to share
Maybe you liked:
(routeData["isLolcat"] as bool?).GetValueOrDefault()
(routeData["isLolcat"] as bool?).GetValueOrDefault(false)
(routeData["isLolcat"] as bool?) ?? false
If not, you will have to write an assistant. I actually recommend using a helper because the code I posted is scary what you mean. I would prefer this:
routeData.GetOrDefault<bool>("isLolcat")
Because it is a document in writing that you intend to.
source to share
Is there some short, readable, easy way to do this, or would I be better off writing a helper extension method?
I would say it's better to write your own extension because you can make your intentions clear
public static class Ext
{
public static T CastOrDefault<T>(this object obj)
{
return obj is T ? (T)obj : default(T);
}
}
...
bool isLolCat = RouteData["isLolCat"].CastOrDefault<bool>();
Sentence. If you want to keep it short, you can call it something likeAs<T>
bool isLolCat = RouteData["isLolCat"].As<bool>();
string str = RouteData["isLolCat"].As<string>(); // null
source to share
I don't think that there is the most common way, all casting / transform operations have their own peculiarities.
For example, it Convert.ToBool
can accept strings to convert, do you want to convert that or won't it work?
x as bool
will give you null if it is not a type bool
.
I think it would be better to write an extension method for RouteData
.
public static T GetValueOrDefault<T>(this RouteData routeData, string field)
{
var value = routeData[field];
if (value is T)
{
return (T)value;
}
return default(T);
}
This way you are working with a class RouteData
and not with potentially null values.
Using:
var isLolCat = routeData.GetValueOrDefault<bool>("IsLolCat");
source to share