Is there a shorthand when checking a boolean for true?
Example:
if (autoConnect) Connect();
We can do
return IsOpen() ? true : false;
But I cant get
autoConnect ? Connect();
running. Is there a way to do this?
You could write an extension method:
public static void _(this bool b, Action ifTrue)
{
if (b) { ifTrue(); }
}
then you could write:
autoConnect._(Connect);
although obviously this is not very readable and is not recommended.
The only thing you can shorten is to remove the conditional operator:
return IsOpen() ? true : false;
and just
return IsOpen();
No, no way to get autoConnect ? Connect(); working.
just return the bool value, don't need a ternary operator:
return IsOpen();
Alternativelly, you return some values when a value you want to test can be null using the ?? operator, for sample:
return a ?? b;
If a is null, then return b.
To answer your question, no, there is no shorthand to make
if (autoConnect) Connect();
any shorter. Also, your proposed solution only saves up 3 characters, which is an unnecessary golfing of otherwise perfectly readable code.
As siride says if (autoConnect) Connect(); is the shortest way. Altough, this is just while writing code. Whenever the compiler compiles the code it will become the same as using if (autoConnect) { Connect(); } or if (autoConnect == true) { Connect(); }.
You should use whatever you find the most clean or easiest reading.
Related
I have the following code:
string thing="";
if(request.Session.Attributes?.TryGetValue("varName", out thing))
{
//do stuff
}
request.Session.Attributes is a dictionary.
I understand that you can't have if(bool?) which is what the above does.
I also know that you can have .GetValueOrDefault() so that null will be treated as false.
But I can't do request.Session.Attributes?.GetValueOrDefault().TryGetValue("varName", out thing)
So what is the correct way to return false if Attributes is null otherwise return the bool from the TryGetValue?
A quick and slightly dirty way is doing:
string thing="";
if(request.Session.Attributes?.TryGetValue("varName", out thing) ?? false)
{
//do stuff
}
In this way you are sure that if Attributes is null, the second branch of the ?? will be chosen and it will not get inside the if.
Personally, I would split it, as having it in a 1-liner does not improve the code that much. It'd become:
string thing="";
var attributes = request.Session.Attributes;
if(attributes != null && attributes.TryGetValue("varName", out thing))
{
//do stuff
}
This is much more readable. Sometimes it is just fair to avoid using new features of the language if they do not improve the code.
Bonus tip:
You can get a line back removing the declaration of things and placing it just after the out 😉:
attributes.TryGetValue("varName", out string thing)
I suspect you're looking for:
if (request.Session.Attributes?.TryGetValue("varName", out thing) == true)
Alternatively:
if (request.Session.Attributes?.TryGetValue("varName", out thing) ?? false)
The null-coalescing ?? operator here is effectively saying "If we didn't call TryGetValue because Attributes is null, this is what I want to pretend it returned."
to set a default value of an nullable type in c# you can use the ?? opperator
if(nullableboolean ?? false){
}
so that would default to false
Something like this:
Dictionary<string,string> stuff = null;
if(stuff?.TryGetValue("key",out string val) ?? false){
Console.WriteLine("hey");
}
This code throws a NullReferenceException if mode is not specified in the pages query string:
bool isAdvancedMode = Request.QueryString["mode"].Equals("advanced");
This is how I work around this:
bool isAdvancedMode = (Request.QueryString["mode"] + "").Equals("advanced");
Is this standard practise, or a hack?
You can use the null-coalescing operator:
bool isAdvancedMode = (Request.QueryString["mode"] ?? String.Empty).Equals("advanced");
Edit: If you want to re-use this logic, try this extension method:
public static bool EqualIfExists(this string source, string comparison)
{
return source != null && source.Equals(comparison);
}
Request.QueryString["mode"].EqualIfExists("advanced")
Add more overrides to match Equals signature. I'm not sure if this is a good name (I think it is not).
Well, I would recommend this instead:
bool isAdvancedMode = (Request.QueryString["mode"] ?? "").Equals("advanced");
In fact, this is what your code compiles to (Nearer the bottom, but it's a good read so I'd read it all). Yours is good practice, but this is a bit more clear.
Why not use the null coalescing operator?
bool isAdvancedMode = (Request.QueryString["mode"] ?? String.Empty).Equals("advanced");
Different approach, while a bit more code, I think is more clear the intent.
bool isAdvancedMode = String.IsNullOrWhitespace(Request.QueryString["mode"]) ?
false : Request.QueryString["mode"].Equals("advanced")
what about this
bool isAdvancedMode=(Request.QueryString["mode"] ?? string.Empty).Equals("advanced");
I have the following statement:
serverCard.Details = !String.IsNullOrEmpty(card.Details) ? card.Details : serverCard.Details;
I want to check and see if card.Details is null or empty... if not, write the value. Is there any syntax that allows me to leave out the else conditional?
Sure, just use a regular if:
if(!String.IsNullOrEmpty(card.Details))
serverCard.Details = card.Details
You can always use the old if statement:
if(!String.IsNullOrEmpty(card.Details))
{
serverCard.Details = card.Details;
}
I think the ternary operator is not needed here.
You can write an extension method for String to check if nullOrEmpty. The regular if then would be shorter
Extension Method:
public static bool IsNullOrEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
public static bool IsNullOrWhiteSpace(this string str)
{
return string.IsNullOrWhiteSpace(str);
}
The if:
if(!card.Details.IsNullOrWhiteSpace())
serverCard.Details = card.Details
The extension method will work for every string.
Here is some example code to get started:
class Foo
{
public bool? IsValid { get; set; }
}
// later in some other function...
void DoStuff( Foo myFoo )
{
myControlState.Visible = myFoo.IsValid.HasValue ? myFoo.IsValid.Value : false;
}
I run into a lot of situations where I have to use a ternary operator like above to properly use a nullable bool. It would be nice if there was a slightly simpler way of getting the value of the bool without throwing exceptions. The code above seems straight-forward but there are much more complex situations where this ends up being a lot of code. I was hoping for something simple like:
myControlState.Visible = GetNullableValue<bool>( myFoo );
Does anyone have any cleaner alternatives to the ternary operator?
you can use the null-coalescing operator if that makes it more readable.
myControlState.Visible = myFoo.IsValid ?? false;
This is more elegant
myControlState.Visible = myFoo.IsValid ?? false;
myControlState.Visible = myFoo.IsValid.GetValueOrDefault();
If you are reading bit values from the SQL server and want to check against null errors, Use the following Extension method against the data Row
public static T GetValueOrDefault<T>(this DataRow row, string key)
{
return row.GetValueOrDefault(key, default(T));
}
and when you are reading data from the SQL server put in.
Boolean IsVisible = GetValueOrDefault<string>("FieldName");
I have a method called isStringOnlyWhitespace():
public static bool isStringOnlyWhitespace(string toEval)
{
string stringNoWhitespace = Regex.Replace(toEval, #"\s", "");
if (stringNoWhitespace.Length > 0) return false;
else return true;
}
Is there any reason to use this method to check for blank/null strings over String.IsNullOrEmpty()?
Sure, if you are shooting for slower code that is harder to read :)
You really want to use string.IsNullOrWhitespace though. Whoever wrote that code might have done so before this method existed. But even still, I'd prefer myString.Trim().Length == 0 in that case.
The method you give doesn't handle nulls whereas String.IsNullOrEmpty does.
That would indicate to me that passing your method a null value is an error condition which is different behavior from String.IsNullOrEmpty.
Also, as others have pointed out, your method would return true for isStringOnlyWhitespace(" ") whereas String.IsNullOrEmpty(" ") would return false.
Yes. Strings containing only whitespace are not considered to be empty. isStringOnlyWhitespace(" ") returns true, but string.IsNullOrEmpty(" ") returns false.
No ;)
a) I think since .net 4 you can use string.IsNullOrWhitespace
b) try something like
public static bool IsStringOnlyWhitespace(this string str)
{
// if you want to check for null:
return str == null || string.IsNullOrEmpty(str.Trim());
// else
return string.IsNullOrEmpty(string.Trim());
}