String.IsNullOrBlank Extension Method - c#

I continuously check string fields to check if they are null or blank.
if(myString == null || myString.Trim().Length == 0)
{
throw new ArgumentException("Blank strings cannot be handled.");
}
To save myself a bit of typing is it possible to create an extension method for the String class that would have the same effect? I understand how extension methods can be added for a class instance but what about adding a static extension method to a class?
if(String.IsNullOrBlank(myString))
{
throw new ArgumentException("Blank strings cannot be handled.");
}

You could do:
public static bool IsNullOrBlank(this String text)
{
return text==null || text.Trim().Length==0;
}
And then call it like this:
if(myString.IsNullOrBlank())
{
throw new ArgumentException("Blank strings cannot be handled.");
}
This works because C# allows you to call extension method on null instances.

I know this is an old question but since it was bumped and it hasn't been mentioned already, as of .NET 4.0 you can simply use the String.IsNullOrWhiteSpace method to achieve the same result.

You can safely use an extension method on the instance:
public static class StringExtensions
{
public static bool IsNullOrBlank(this string s)
{
return s == null || s.Trim().Length == 0;
}
}
Test cases:
string s = null;
Assert.IsTrue(s.IsNullOrBlank());
s = " ";
Assert.IsTrue(s.IsNullOrBlank());
It looks a bit weird though, and I would instead figure out why your strings need to be checked for this case so often. If you fix them at the source, you won't have to be so paranoid about them later!

Can you add static methods to existing classes? The answer is no, and the value would be pretty thin, because you'd still need to know which class name to type first; with extension methods, the advantage is that you start with a variable name and autocompletion shows you things that are applicable to it.
Another point often made is that extension methods should always throw an exception as soon as possible if their first argument is null. However, I think that rule is overkill if the method mentions in its name that it is designed to check for null.
The real problem you have is that you want to neatly and readably run some code after checking for a null reference. One way to capture that pattern is in my answer to this question.

An overload to the existing answers could be:
public static bool IsNullOrBlank(this String text, Action<String> doWhat)
{
if (text!=null && text.Trim().Length>0)
doWhat(text);
}
Would be helpful if you only want to run code given a valid value.
Not a super useful example, but just showing the usage:
Name.IsNullOrBlank(name=>Console.WriteLine(name));

A bit late. But you can also put the code to throw an exception in an extension method too. I have two methods (for ArgumentNullException and NullReferenceException).
// strings
public static bool NullBlankCheck(this string s, string message = "",
bool throwEx = true)
{
return Check<NullReferenceException>(s.IsNullOrBlank(), throwEx, message);
}
public static bool NullBlankCheckArgument(this string s, string message = "",
bool throwEx = true)
{
return Check<ArgumentException>(s.IsNullOrBlank(), throwEx, message);
}
private static bool Check<T>(bool isNull, bool throwEx, string exceptionMessage)
where T : Exception
{
if (throwEx && isNull)
throw Activator.CreateInstance(typeof(T), exceptionMessage) as Exception;
return isNull;
}
public static bool IsNullOrBlank(this string s)
{
return string.IsNullOrEmpty(s) || s.Trim().Length == 0;
}
nunit tests:
Assert.Throws<NullReferenceException>(() =>
{
"".NullEmptyCheck();
});
Assert.Throws<ArgumentException>(() =>
{
"".NullEmptyCheckArgument();
});
And then use it as:
public void Method(string someStr)
{
someStr.NullBlankCheckArgument();
// do something
var str = someMethod();
str.NullBlankCheck();
}

public static bool IsNullOrEmptyTrimmed(string value)
{
return (value == null || value.Length == 0) ?
true : value.Trim().Length == 0;
}
or
public static bool IsNullOrEmpty(this String value, bool checkTrimmed)
{
var b = String.IsNullOrEmpty(value);
return checkTrimmed ? (b && value.Trim().Length > 0) : b;
}

Although, this question was asked over a decade ago, I see no one has mentioned that there is a built in string method for handling this.
Therefore, please use string.IsNullOrWhitespace() instead. No hacking anything in, use the language feature and you're just fine.

With a few tricks, you make it look like you've added to the String class in any one cs file:
namespace JDanielSmith
{
public static class String
{
public static bool IsNullOrBlank(string text)
{
return text == null || text.Trim().Length == 0;
}
}
}
(note, this is not an extension method, see my comment).
Then, in some other CS file:
using String = JDanielSmith.String;
namespace Foo.Bar.Baz
{
class Program
{
static void test(string myString)
{
if (String.IsNullOrBlank(myString))
{
throw new ArgumentException("Blank strings cannot be handled.");
}
}
...
Notice the "desired" syntax of String.IsNullOrBlank(). I'm not necessarily suggesting that you actually do things this way, just pointing out how you could set things up to make your code work.

public static bool IsNull(this object o)
{
return string.IsNullOrEmpty(o.ToStr());
}
public static bool IsNotNull(this object o)
{
return !string.IsNullOrEmpty(o.ToStr());
}
public static string ToStr(this object o)
{
return o + "";
}

Related

Universal DBNull check

I have a VB.Net function that is useful for checking if a database record is null or not, and replace it with a default value if it is.
Public Function NZ(input As Object, Optional ifNull As Object = "") As Object
If IsDBNull(input) Or input Is Nothing Then
Return ifNull
Else
Return input
End If
End Function
I'm trying to get the same functionality in C#, but it doesn't like using objects the same way.
The closest I've gotten is
public static object NZ(object input, object ifNull)
{
if(input == DBNull.Value || input == null)
{
return ifNull;
}
else
{
return input;
}
}
but I get several errors with "cannot convert object to string" and the like.
I have tried to make a more specific version
public static string NZ(string input, string ifNull)
{
if (input == DBNull.Value || input == null)
{
return ifNull;
}
else
{
return input;
}
}
but that gives a "Operator '==' cannot be applied to operands of type string and DBNull"
I'm hoping there is an easy way to do this.
Use Convert.IsDbNull
The code will be something like this:
public static string NZ(object input, string ifNull)
{
return Convert.IsDbNull(input) ? ifNull : input;
}
If you want it to be more concise, write an extension method:
public static class DbNullExt
{
public static string ValueOrDefault(this object input, string ifNull)
=> Convert.IsDbNull(input) ? ifNull : input?.ToString();
public static string ValueOrDefaultIfDbNullOrNull(this object input, string ifNull)
=> Convert.IsDbNull(input) ? ifNull : input?.ToString() ?? ifNull;
}
And then simply invoke it as
var valueOrDefault = input.ValueOrDefault("ifItIsDbNull");
Use Information.IsDBNull
public object NZ(object input, object ifNull)
{
if (Information.IsDBNull(input) || input == null)
return ifNull;
else
return input;
}

Is extension method for convertion thread safe

Please consider this code:
public static int ToInt (this string str)
{
return Convert.ToInt32 (str);
}
Should I use lock for this statment?
EDIT 1)
public static int ToInt(this string str)
{
int Id = -1;
if (str.IsEmpty() == true ||
int.TryParse(str.Trim().Replace(",", ""), out Id) == false)
{
throw new Exception("Invalid Parameter: " + str);
}
else
{
return Id;
}
}
is this method thread-sate too?
No, a lock is not necessary.
string is immutable; and so another thread cannot change its contents while you are trying to parse it.
It really doesn't have anything to do with extension methods; those may or may not be thread-safe based on what they do (or what parameters they take).
Besides; unless the lock was respected elsewhere in the code; doing so wouldn't change anything... (again, at least for this method)

c# private and overload functions [duplicate]

This question already has answers here:
What's a "static method" in C#?
(9 answers)
Closed 8 years ago.
Why is MainWindow/this.ab hidden and cannot be seen? I suppose private should be seen inside mainWindows.
It seems like C# throws error Not all code return path value if I put return not at the end of the method.
Can c# return string and void at the same time? If I am wrong, what is the better code? In PHP,the code easily works. I need to know how it can get to work in C#.
public static string a(string type,string a)
{
return MainWindow.ab(type, a);
}
public static void a(string type)
{
MainWindow.ab(type);
}
private string ab(string type,string a=null)
{
if (type == "1")
{
return "1";
}
}
Better code is
public static string a(string type,string a)
{
return MainWindow.ab(type, a);
}
public static string a(string type)
{
return MainWindow.ab(type);
}
private static string ab(string type,string a=null)
{
if (type == "1")
return "1";
else
return null;
}
Why does MainWindow/this.ab is hidden and cannot be see ?
Because method is not correct and is not static.
Can c# return string and void same time ?
No, you can return null instead using of void
If you want to use 'ab' method as you use it in your example, ab should be defined as follows inside MainWindow:
public static string ab(...)
In regard of "return" error - not all execution paths return a string, e.g. if type != "1", return value is not provided.

Enable static contract checker to prove a Property non-null based on some other property

Assume the following code:
public class CC3
{
private string _field;
private bool _someFlag;
public string Property
{
get { return _field; }
}
public bool SomeFlag
{
get { return _someFlag; }
}
public void SetField()
{
_field = " foo ";
_someFlag = true;
}
public string Method()
{
Contract.Requires(SomeFlag);
return Property.Trim();
}
}
The static checker of Code Contracts complains about the return statement of Method:
Possibly calling a method on a null reference 'this.Property'
What do I have to do to enable the static checker to prove that Property can never be null if SomeFlag is true?
You can give the static analysis a helping hand using Contract.Assume:
public string Method()
{
Contract.Requires(SomeFlag);
Contract.Assume(Property != null);
return Property.Trim();
}
Or actually add the check as a Contract.Requires in its own right. After all, just because you can manually prove it to be true for now, you can't guarantee that will always be the case when the code gets modified. In fact, consider whether SomeFlag being true is actually a requirement at all. Perhaps this is a cleaner solution:
public string Method()
{
Contract.Requires(Property != null);
return Property.Trim();
}
The only way to prove that it is not null is to prove that it is not null. Ideally you could use an invariant if you would convert to auto properties. For this example you could rewrite the property to ensure that null is not a possible result:
public string Property
{
get {
Contract.Ensures(Contract.Result<string>() != null);
return _field ?? String.Empty;
}
}

Saying the contract static checker that a extension method not allow null?

Contract.Requires(completeURL.IsUri()); // Error: Contract.Requires(completeURL != null)
Can I do this without Contract.Assume()?
I mean something like this:
[Pure]
[DefinitelyNotANullStringAfterThatMethod]
public static bool IsUri(this string str)
{
return Uri.IsWellFormedUriString(str, UriKind.Absolute);
}
[Pure]
public static bool IsUri(this string str)
{
Contract.Ensures(!Contract.Result<bool>() || str != null); // by Dan Bryant
return Uri.IsWellFormedUriString(str, UriKind.Absolute);
}
Maybe?
In my experience, having contracts like this which require validation methods makes things very hard on yourself.
If you change the signature of the method so that it takes a Uri rather than a string, you make life simpler - as it has to be a valid Uri.
[Pure]
public static bool IsUri(this string str)
{
Contract.Ensures(!Contract.Result<bool>() || str != null); // by Dan Bryant
var result = Uri.IsWellFormedUriString(str, UriKind.Absolute);
Contract.Assume(!result || str != null);
return result;
}

Categories