Best Practise in String Methods

Cp_raj
Posted by in C# category on for Beginner level | Views : 6008 red flag

String Method
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.



Page copy protected against web site content infringement by Copyscape

About the Author

Cp_raj
Full Name: Rajkumar Pauldurai
Member Level: Starter
Member Status: Member
Member Since: 5/26/2009 6:29:52 AM
Country:

http://www.dotnetfunda.com
I started my career with Asp,ms-access,sql server 7,xml.Then i updated to .net,share point server,Basics about Biztalk server

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)