Can you tell me if TrimNull() is redundant and if I should be using an alternative?
For example:
string username = UsernameTextBox.Text.TrimNull();
I am told there is no definition or extension method. Perhaps there is a reference I am missing?
UPDATE:
What is the most readable way to return empty string if the value is NULL?
There's no such function as TrimNull(String) - it wouldn't do anything. A string is either a null or not null, it can't contain a mixture of both. If the string were null, a static function TrimNull(myString) would not be able to 'remove' anything from the string. If it weren't null, there would be no NULL to remove. Even worse, if TrimNull were an instance method myString.TrimNull() would simply cause an exception if myString were NULL - because you cannot invoke any method on a null reference.
If your goal is to trim whitespace characters surrounding the string, just use myString.Trim().
If your goal is to detect whether the string is null, use myString == NULL
If your goal is to detect whether the string is empty or null use String.IsNullOrEmpty(myString)
If your goal is to trim trailing null characters (\0) from data stream, try the following:
myString.TrimEnd(new char[] { '\0' } )
But as Frédéric Hamidi said, if you're referring to the latter, the user will have a hard time getting null characters into a TextBox, so you shouldn't worry about that scenario in your processing of their input.
I usually use String.IsNullOrWhiteSpace(), like this:
string username = (String.IsNullOrWhiteSpace(UsernameTextBox.Text) ?
null : UsernameTextBox.Text.Trim());
That way, if the .Text property is null, it doesn't cause an exception.
You could create your own extension-method for that, if you like:
public static class StringExtensions
{
public static string TrimNull(this string value)
{
return string.IsNullOrWhiteSpace(value) ? value : value.Trim();
}
}
Add this to your project and your code will work.
This is just an alternative.
Use null-coalescing operator as mentioned in #sixlettervariables answer in Negate the null-coalescing operator
string username = (UsernameTextBox.Text ?? String.Empty).Trim();
A string being NULL is not its value. its a state. It means it has not been assigned a memory (coz its a reference type). Had it been a value type datatype it woudld be assigned a default value automatically like for int its 0 and so on
u should use
if(!String.IsNullOrEmpty(UsernameTextBox.Text))
string username = UsernameTextBox.Text.Trim();
Related
In C# .net, if I take a string.Empty and call .FirstOrDefault() on it, intending to get the first character of the string, It will return a null character reference i.e. \0, and not a null character i.e. char?. Then casting this ToString() does not have the same value as string.Empty
So based on my testing the following statements appear to resolve to true:
string.Empty.FirstOrDefault().ToString() != string.Empty
((char?)null).ToString() == string.Empty
string.Empty.FirstOrDefault().ToString() == '\0'.ToString()
Is it just me or does this feel inconsistent? This wasn't obvious to me initially and I had assumed that string.Empty.FirstOrDefault().ToString() would resolve to the same value as string.Empty. Can anybody link me to documentation that covers this gotcha in more depth?
string is an IEnumerable<char>, so FirstOrDefault() on an empty string returns default(char), not default(char?).
default(char) is '\0'.
It is (almost) impossible to write a generic method that works on references types but returns T? for value types (which is what you're expecting here).
string.Empty = "" is array of chars of length 0.
string.Empty.FirstOrDefault() is default(char) which is '\0' (FirstOrDefault<T> returns default(T) if source is empty)
string.Empty.FirstOrDefault().ToString() = default(char).ToString() = "\0"
char? is Nullable<char>, if you check ToString() implementation for Nullable
public override string ToString()
{
if (!this.hasValue)
return "";
return this.value.ToString();
}
which means, ((char?)null).ToString() returns "" (or string.Empty).
the most of the time when I work with C# and need to validate a null or empty string I use the method:
if (String.IsNullOrEmpty(s))
return "is null or empty";
else
but now I need to use this in this way:
string value= data.value==null?DBNull.Value:data.value;
I try to use both in the last sentence getting this
string value= String.IsNullOrEmpty(data.value)?DBNull.Value:data.value;
but always return true even is there is not any value in the property data.value, BTW data.value is a string, could you please tell me if my sentence is right or what seems to be the problem?
First off you cant use string value = DBNull.Value because those types are not compatible. You have to cast back to the common type which is System.Object so then the assignment becomes this which uses casting to ensure type compatibility:
object value = String.IsNullOrEmpty(data.value)
? (object) DBNull.Value
: (object) data.value;
If you want to check for white space you can use IsNullOrWhiteSpace instead of IsNullOrEmpty
I am wondering if there is a special method/trick to check if a String object is null. I know about the String.IsNullOrEmpty method but I want to differentiate a null String from an empty String (="").
Should I simply use:
if (s == null) {
// blah blah...
}
...or is there another way?
An object can't be null - the value of an expression can be null. It's worth making the difference clear in your mind. The value of s isn't an object - it's a reference, which is either null or refers to an object.
And yes, you should just use
if (s == null)
Note that this will still use the overloaded == operator defined in string, but that will do the right thing.
You can use the null coalescing double question marks to test for nulls in a string or other nullable value type:
textBox1.Text = s ?? "Is null";
The operator '??' asks if the value of 's' is null and if not it returns 's'; if it is null it returns the value on the right of the operator.
More info here:
https://msdn.microsoft.com/en-us/library/ms173224.aspx
And also worth noting there's a null-conditional operator ?. and ?[ introduced in C# 6.0 (and VB) in VS2015
textBox1.Text = customer?.orders?[0].description ?? "n/a";
This returns "n/a" if description is null, or if the order is null, or if the customer is null, else it returns the value of description.
More info here:
https://msdn.microsoft.com/en-us/library/dn986595.aspx
To be sure, you should use a function to check for null and empty as below:
string str = ...
if (!String.IsNullOrEmpty(str))
{
...
}
If you are using C# 7.0 or above you can use is null:
if (s is null) {
// blah blah...
}
Also, note that when working with strings you might consider also using IsNullOrWhiteSpace that will also validate that the string doesn't contain only spaces.
For .net 5 (probably also for .net Core 3.1)
Different possibility to write but always the same problem.
string wep = test ?? "replace";
Console.WriteLine(wep);
result: "replace"
or
string test=null;
test ??= "replace";
Console.WriteLine(test);
test="";
test??="replace";
Console.WriteLine(test);
first try: "replace"
second try: blank
string test="";
if(test is null)
Console.WriteLine("yaouh");
else
Console.WriteLine("Not yahouu");
Result: "Not yahou"
You can check with null or Number.
First, add a reference to Microsoft.VisualBasic in your application.
Then, use the following code:
bool b = Microsoft.VisualBasic.Information.IsNumeric("null");
bool c = Microsoft.VisualBasic.Information.IsNumeric("abc");
In the above, b and c should both be false.
I'm used to using VB.net for web programming.
Often, I have something like:
Dim s as string = Session("s")
I get a string value for s from the web session. If there is no value in the web session, I get a blank string.
However, AFAIK, in C#, I have to have something like the code below to do the same thing.
string s;
try { s = Session["s"].ToString(); }
catch { s = ""; }
Is there an easier way to do this?
This is a quick way of doing this:
s = (string)Session["s"] ?? "";
This will cast Session["s"] to a string, and if it is not null, return the value. If it is null, it will return an empty string. The "a ?? b" expression is essentially the same as "a != null ? a:b" (?? is compiled more efficiently though)
Something else to keep in mind: you should never use exceptions for normal application logic.
Because string is reference type then is nullable, so you can check for empty or null by means of string.IsNullOrEmpty(s):
string s = string.IsNullOrEmpty((string)strObject) ? string.Empty : strObject.ToString();
Otherwise (as Philippe Leybaert says) you can use ?? operator.
I almost agree to Philippe, but it only works if "s" is present in the session, otherwise there will be a KeyNotFoundException. This code checks it, but does not solve the NULL issue of Philippe.
s= Session.ContainsKey("s")?Session["s"]:"";
So to cover both possibilities, it becomes mre complex:
s = Session.ContainsKey("s")?(Session["s"]??""):"";
It does not really make it easier, but the performance should be better than catching an exception.
I have a bunch of strings I need to use .Trim() on, but they can be null. It would be much more concise if I could do something like:
string endString = startString !?? startString.Trim();
Basically return the part on the right if the part on the left is NOT null, otherwise just return the null value. I just ended up using the ternary operator, but is there anyway to use the null-coalescing operator for this purpose?
You could create an extension method which returns null when it tries to trim the value.
public String TrimIfNotNull(this string item)
{
if(String.IsNullOrEmpty(item))
return item;
else
return item.Trim();
}
Note you can't name it Trim because extension methods can't override instance methods.
Not to spec: Not that I like it, but you could use:
string endString = (startString ?? String.Empty).Trim();
To spec, better as an Extension method like #Kevin's:
string endString = (startString == null ? null : startString.Trim());
string endString = string.IsNullOrEmpty(startString) ? startString : startString.Trim();
Though I've also gone the route of writing a string extension method called "safeTrim" which does what you're describing in one method instead of having to use this recipe every time. Check out Kevin's respone for the code.
EDIT: wow I had it all kinds of backwards, wrongly named variables and reversed ternary operators, all the more reason to write one extension method and code check it better than I did!
Starting with C# 6.0 (.NET Framework 4.6 / Visual Studio 2015) you can use null-conditional member access:
string? endString = startString?.Trim();
Sorry for the necromancy, but I was having this same problem and I solved this using a lambda operation. It isn't the prettiest, but it keeps my code succinct.
It's a shame C# doesn't support static imports or individual function imports, but anyway:
Define this function somewhere:
private static TResult N<TParent,TResult>(TParent parent, Func<TParent,TResult> operation) {
if( parent == null ) return default(TResult);
return operation( parent );
}
Then to use it in your example:
String endString = N(startString, s => s.Trim());
The N function returns null if the first argument is null, otherwise it will evaluate the specified lambda function with the value as the argument.
You can nest it, of course, like so. For example, to safely dereference a long chain, e.g.
String someValue = someObject.SomeProperty.SomeOtherProperty.SomeMethod().SomeFinalProperty;
if any of those properties or methods returns null then you have to insert null checks everywhere, or you could do this:
String someValue = N(N(N(N(someObject, o => o.SomeProperty), o => o.SomeOtherProperty), o => o.SomeMethod()), o => o.SomeFinalProperty);
As I said, it isn't the prettiest :)
You could simplify this by making N an extension method of System.Object, like so:
String someValue = someObject.N( o => o.SomeProperty ).N( o => o.SomeOtherProperty ).N( o => o.SomeMethod() ).N( o => o.SomeFinalProperty );
...which I think is a lot tidier.
Use
string endString = (startString ?? "").Trim();
This uses an empy string if startString is null. This, however, does not return null when endString is null.
Fast-forward to 2021:
10 years later startString?.Trim() is definitely the better option. And this does return null.
The following doesn't propagate null but it accepts null as a parameter and returns an empty string in that case.
using Microsoft.VisualBasic; // you need to add a reference to Microsoft.VisualBasic.dll
...
string endString = Strings.Trim(startString);
...
duck&run...
As as side note, if you're using .NET 4, there's a new convenient method String.IsNullOrWhiteSpace which you can use.