How to output to console a bool? - c#

I want a concise way to output a bool? in c#. Currently, I am doing this which is very bulky.
string outputString = boolValNullable.HasValue && boolValNullable.Value ? "true" : "false";
I want to do something like:
string outputString = boolValNullable ?? "null"
The above is invalid syntax.

string output = boolValNullable?.ToString() ?? "null"

This should do the trick for you. Pass in your bool to this method and it will output to your console.
public void OutputBoolToConsole(bool? myBool)
{
var myBoolAsString = myBool?.ToString() ?? "bool is null";
Console.WriteLine(myBoolAsString);
}

Actually, you can use a conditional operator ?: for that
string outputString = boolValNullable.HasValue ? boolValNullable.Value.ToString() : "null";
or simply use Nullable<T>.ToString() method, if you want to get an empty string in case of boolValNullable equals null
string outputString = boolValNullable.ToString();
It returns
The text representation of the value of the current Nullable<T> object
if the HasValue property is true, or an empty string ("") if the
HasValue property is false.
Boolean.ToString method returns either True of False (the first letter is capital). If you need a lower case, you should add ToLower() call after ToString()

Related

Why does a null value automatically get converted into empty string when using string.Join?

I have a JArray that contains null values. And while I'm doing string.Join, null values are getting converted into empty string.
Original array values:
[
null,
null,
"America/Boise",
false,
"2021-02-04T06:51:33.9686227Z"
]
String.Join:
var val = $"('{string.Join("','", valuesArray)}')";
Current Result:
"('','','America/Boise','False','2/4/2021 6:51:33 AM')"
Expected Result:
"(null,null,'America/Boise',False,'2/4/2021 6:51:33 AM')"
Producing Example:
https://dotnetfiddle.net/5nRTyL
How do I get the expected result using string.Join?
null values in a JArray are stored as JTokens with a JTokenType of Null. So you'll need to check for this and convert them to the string "null". Secondly, since you only want to quote some of the values, you should not put the quotes in the separator value when you join them, but instead only quote the values that need it based on their types.
Define the following helper function:
string TokenToString(JToken token)
{
switch (token.Type)
{
case JTokenType.Null:
return "null";
case JTokenType.Date:
case JTokenType.String:
return $"'{token}'";
default:
return token.ToString();
}
}
Then you can get the result you want like this:
string val = $"({string.Join(",", valuesArray.Select(v => TokenToString(v)))})";
Working demo here: https://dotnetfiddle.net/Q62Uck
Because that's how it was designed. See the documentation for String.Join:
If separator is null, an empty string (String.Empty) is used instead. If any element in value is null, an empty string is used instead.
just replace "''" to "null".
var val = $"('{string.Join("','", valuesArray)}')".Replace("''", "null");

Difference between "" (Empty String) and isNot Nothing?

I am working on a condition where I have to validate whether the argument is empty or not. Lets assume that argument is Email. I have to check whether the inwards argument Email is empty or not. I can do it in several way but I am not sure which one to proceed with.
I am thinking to check from following statement:
1.Email = "" to check if email is empty string or not.
2. Email isNot Nothing
I wanna know the difference of these two functionality. If there are more function or argument related to validating empty string, You can write that too.
Thanks.
String is a reference type, which means it can have a null reference
Eg
string myString = null;
It can also be empty, which is to say, there is a reference to it, and it has 0 character length
Eg
string myString = "";
// or
string myString = string.Empty;
And just for completeness, it can also have white space
Eg
string myString = " ";
You can check for null like so
if(myString == null)
You can check for empty
if(myString == "")
// or
if(myString == string.Empty)
You can check for both, not null and not empty
if(myString != null && myString != string.Empty)
You could use Null conditional Operator with Length to check both is not null and not empty
if(myString?.Length > 0)
Or you can use the built in string methods, to make it a little easier
String.IsNullOrEmpty(String) Method
Indicates whether the specified string is null or an empty string
("").
if(string.IsNullOrEmpty(myString))
String.IsNullOrWhiteSpace(String) Method
Indicates whether a specified string is null, empty, or consists only
of white-space characters.
if(string.IsNullOrWhiteSpace(myString))
Note : It's worth noting, that IsNullOrWhiteSpace generally more robust when checking user input
Actually in C# string.Empty is equivalent to "". See String.Empty
Best way to check for Empty or Null strings is:
string.IsNullOrEmpty(Email) or you can use string.IsNullOrWhiteSpace(Email) to additionally check for white spaces.
if(!string.IsNullOrEmpty(Email))
{
// Good to proceed....
}
You should not use IsNot nothing with reference type variable. Instead, Use string.IsNullOrEmpty(Email) together with String.IsNullOrWhiteSpace(Email) while you need to validate email.

(one line if) ? bool is true - give me string [duplicate]

This question already has answers here:
Ternary with boolean condition in c#
(7 answers)
Closed 5 years ago.
I can't wrap by head around this even though I've read many stackoverflow threads.
I check if the page has a specific property value like so:
bool categoryCount = CurrentPage.HasValue("blogCategories");
I want to transform this into a one-line if statement so I can parse a string to a class like illustrated below:
string situation = (categoryCount.ToString() == "true") ? '' : '';
PS: I apologize for the missing logic behind my thoughts/goal. I'm new at programming.
What about:
string situation = (CurrentPage.HasValue("blogCategories"))
? "Has the value" : "Has NOT that value";
You should change two things:
do not work with ToString() == "True", simply put the boolean (expression) in the condition part of the ternary operator: it is inefficient to call ToString() and furthermore if the specifications change, it might stop working (actually true.ToString() returns "True", with a capital, so it will not work with your code);
use string literals "some string", not char literals 'a': the result is supposed to be a string, not a char.
By comparing with "true", this will not work:
csharp> true.ToString()
"True"
csharp> true.ToString() == "true"
false
But even if it would work, it would be rather unsafe: if later the designers of the .NET library change their minds, then your program could stop working correctly. Usually I think it is better not to rely on the format of a ToString() method. These tend to be culture specific, and furthermore usually do not offer hard constraints with respect to the output format anyway.
You don't need to convert to string to use ternary. You can simply just do this:
string situation = categoryCount ? "Executes if true" : "Executes if false";
The ternary condition doesn't need to be a string, just the returns.
You don't need to convert a bool to a string to find out if it's true.
Do you know what this returns if categoryCount has the boolean value true?
bool x = categoryCount.ToString() == "true";
It returns the boolean value true. If categoryCount is true, then it is true that its string representation is equal to "true". But categoryCount is true already.
It is exactly the same as this:
bool x = categoryCount;
Also, a string in C# uses double quotes, not single quotes.
So:
string situation = categoryCount ? "one string" : "another string";

I need a function that I can apply to a string to return the string value or "00" if it is null

Is there some function that I can apply to a string so that the string will return its value if the string is not equal to null or the value "00" if it is null.
var abc = myVariable.xxxx;
gives abc = "AB" if myVariable == "AB";
gives abc = "00" if myVariable == null;
Sounds like you want:
var abc = myVariable ?? "00";
This uses the null-coalescing operator.
string abc = myVariable ?? "00";
You could create a String Extension Method to encapsulate the answer that #JonSkeet gave.
Create a new class in your project called ExtensionMethods or whatever you would prefer and put the extension method in that class e.g.
static class Extensions
{
public static String ConvertNullValue(this String value)
{
return value ?? "00";
}
}
You could then use this extension method against your string variable myVariable like this:
var abc = myVariable.ConvertNullValue();
string abc = myVariable.xxxx ?? "00"

.Trim() when string is empty or null

I'm receiving some data from the client in the form of json.
I'm writing this:
string TheText; // or whould it be better string TheText = ""; ?
TheText = ((serializer.ConvertToType<string>(dictionary["TheText"])).Trim());
If the variable that's being parsed from json comes back empty, does this code crash when I call the .Trim() method?
Thanks.
You can use elvis operator, also known as "null-conditional-operators":
GetNullableString()?.Trim(); // returns NULL or trimmed string
More info: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators
If the serializer returns an empty string, Trim will do nothing.
If the serializer returns null, you will get a NullReferenceException on the call to Trim.
Your code would be better written (as far as initialization is concerned) like this:
string theText =
((serializer.ConvertToType<string>(dictionary["TheText"])).Trim());
There is no point in declaring and initializing the variable and the immediately assigning to it.
The following would be safest, if you don't know what the serializer might return:
string theText = ((serializer.ConvertToType<string>(dictionary["TheText"])));
if(!string.IsNullOrEmpty(theText))
{
theText = theText.Trim();
}
Calling Trim() on an empty string will result in an empty string. Calling Trim() on null will throw NullReferenceException
If you have a few fields you wish to trim but your getting exceptions for those records that have nulls in certain fields, then writing a quick extension method will be the easiest method:
public static class ExtensionMethods
{
public static string TrimIfNotNull(this string value)
{
if (value != null)
{
return value.Trim();
}
return null;
}
}
Sample example of use:
string concatenated = String.Format("{0} {1} {2}", myObject.fieldOne.TrimIfNotNull(), myObject.fieldTwo.TrimIfNotNull(), myObject.fieldThree.TrimIfNotNull());
Some basic techniques to check strings against null before you trim:
(mystring ?? "").Trim()
The "null coalescing operator" ?? will return the first operand. Only when this operand is null, the second operand will be returned (as a kind of default value).
The above example will return an empty string if mystring is null.
mystring?.Trim()
The "null conditional operator" ? will short cirtuit a chain of operations in dot-notation. If the operand is null, the following operations will not be executed and null will be returned.
The above example will return null if mystring is null.
if( string.IsNullOrWhiteSpace(mystring) ) { ... }
the IsNullOrWhiteSpace() method may replace trimming if you actually want to check if there is real content in mystring. It returns true if the operand is null, empty, or nothing but whitespace characters.
As suggested in some of the comments, you may now use c# 6 Null-conditional operators with this syntax:
string TheText = (serializer.ConvertToType<string>(dictionary["TheText"]))?.Trim();
Documentation: https://msdn.microsoft.com/en-us/library/dn986595.aspx
No, it would not be better to initialize TheText to "". You're assigning to it right afterwards.
No, it won't crash – Trim() works just fine on an empty string. If by "empty" you mean that it can be null, then yes, it will crash; you could have null remain null with a null-conditional call:
string TheText =
serializer.ConvertToType<string>(dictionary["TheText"])?.Trim();
You can use the null-safe operator trim of org.apache.commons.lang
StringUtils.trim(stringOrNull)
You can use this code as beblow
string theText = (((serializer.ConvertToType<string>(dictionary["TheText"])))+ string.Empty).Trim();
Recently I had to check a string if it is null, empty or whitespace using just one if condition and for that I found out that you can add "" to a null string to make it non null.
string test = GetStringFromSomeWhere(); // null
if(string.IsNullOrEmpty(test.Trim())) { return true; } // Exception
So I did this instead
string test = GetStringFromSomeWhere() + ""; // ""
if(string.IsNullOrEmpty(test.Trim())) { return true; } // true

Categories

Resources