Introduction
I just take this as a sample for best practices.Still lots of methods avail in C#.
String.isNullOrEmpty()
During coding to check the string whether it is null or empty in .net 1.1 we use to check like this.
if (s != null && s != "")
{
return "Is not null or empty";
}
else
{
return "Is null or empty";
}
But in .Net 2.0 framework they introduced String.IsNullorEmpty (). It will return true if the string variable is empty or Null. Use this as best practice.
While doing code review using FxCop if you use the old method(if (s != null && s != "")) it will advice your to use String.IsNullorEmpty() method.
if (string.IsNullOrEmpty(s) == true)
{
return "Is null or empty function";
}
else
{
return "Is not null or empty function";
}
String.Compare()
To Compare string
We use to code like this.
string s = "abcd";
string s1 = "Abcd";
if (s==s1)
{
return "both are equal";
}
else
{
return "Both are not equal";
}
O/P – Both are not equal.
Even in .net 1.1 we have a method call Compare().It has lot of overloaded methods in that I have taken (string,string,bool ignorecase).To compare string use this.The last parameter is to check the case sensitive.If you give “true” then it will ignorecase sensitive.
if (string.Compare(s, s1, false) == 0)
{
return "both are equal";
}
else
{
return "Both are not equal";
}
O/p : Both are not equal.
Conclusion
In .Net 3.5 Microsoft had added lots of new methods. If any of the string method is not available use Extension methods available in .Net 3.5.
If you like this article, subscribe to our
RSS Feed. You can also
subscribe via email to our Interview Questions, Codes and Forums section.