C# Best Practices - Handling Strings
Features
Strings Are Immutable.
A String Is a Reference Type
Value Type
Store their data directly
Example: int, decimal, bool, enum
Reference Type
Store references to their data
Example: string, object
String Method Best Practices
Do:
Look at what .NET provides before writing your own
Use Intellisense to view the list of available methods
Avoid:
Calling string methods on null strings
Handling Nulls
String.IsNullOrWhiteSpace(cendor)
vendor?.ToLower();
Do:
Write unit tests that cover null conditions
Use IsNullOrWhiteSpace when testing for null in a block of code
Use the null-conditional operator ? when checking for null in a single statement
Verbatim String Literal
var directions = @"Insert \r\n to define a new line";
Insert \r\n to define a new line
Do:
Use verbatim string literals when the string contains special characters such as backslashes.
Use verbatim string literals to hold folder or file names, @"c:\mydir\myfile.txt"
Use two quotes to include quotes in a verbatim string literal, @"Say it with a long ""a"" sound"
Avoid:
Using verbatim string literals when there is no reason, @"Frodo"
String.Format
Do:
Use String.Format to insert the value of an expression into a string
Include a formatting string as needed, like String.Format("Deliver by:{0:d}", deliveryBy))
Avoid:
Use String.Format when concatenating string literals, like String.Format("Hello {0}", "World");
String Interpolation
var pc = String.Format("{0}-{1}", product.Category, product.SequenceNumber);
var pc = $"{product.Category}-{product.SequenceNumber}";
StringBuilder
Conceptually a mutable string
Allow string operations, such as concatenation, without creating a new string
Provides methods for manipulating the mutable string - Append, Insert, Replace, etc
Use ToString to convert a string
More efficient when working with strings that are
- Build up with many separate concatenation operations
- Changed a large number of times, such as within a loop
Do:
Use StringBuilder when building up a string with numerous concatenation operations
Use StringBuilder when modifying a string numerous times (such as a loop)
Consider readability
Avoid:
Use StringBuilder when only modify a string a few times
FAQ
1.What does it mean to say that C# strings are immutable?
It means that strings cannot be modified once they are created.
2.Is a string a value type or a reference type?
A string is a reference type, but acts like a value type.
3.What is the best way to check for null string?
Use String.IsNullOrWhiteSpace is great when checking nulls for a code block
Use the new C# 6 null-conditional operator ? is great for code statements
4.What are the benefits to using StringBuilder?
The .NET StringBuilder class is mutable, meaning that it can be readily changed.
Using StringBuilder is therefore more efficient when appending lots of strings.
C# Best Practices - Handling Strings的更多相关文章
- [翻译] GONMarkupParser
GONMarkupParser https://github.com/nicolasgoutaland/GONMarkupParser NSString *inputText = @"Sim ...
- str_replace vs preg_replace
转自:http://benchmarks.ro/2011/02/str_replace-vs-preg_replace/ 事实证明str_replace确实比preg_replace快. If you ...
- MySQL 中的 FOUND_ROWS() 与 ROW_COUNT() 函数
移植sql server 的存储过程到mysql中,遇到了sql server中的: IF @@ROWCOUNT < 1 对应到mysql中可以使用 FOUND_ROWS() 函数来替换. 1. ...
- nodejs(三)Buffer module & Byte Order
一.目录 ➤ Understanding why you need buffers in Node ➤ Creating a buffer from a string ➤ Converting a b ...
- Zend API:深入 PHP 内核
Introduction Those who know don't talk. Those who talk don't know. Sometimes, PHP "as is" ...
- Java实现LeetCode_0020_ValidParentheses
package javaLeetCode.primary; import java.util.Scanner; import java.util.Stack; public class ValidPa ...
- OSCP Learning Notes - Privilege Escalation
Privilege Escalation Download the Basic-pentesting vitualmation from the following website: https:// ...
- Java – Top 5 Exception Handling Coding Practices to Avoid
This article represents top 5 coding practices related with Java exception handling that you may wan ...
- Exception (3) Java exception handling best practices
List Never swallow the exception in catch block Declare the specific checked exceptions that your me ...
随机推荐
- Linux 安装g++
g++ 它的全名不叫g++而是叫gcc-c++; 所以要安装它就可以用 yum install gcc-c++;
- QR Code於台灣各行業的行銷應用案例介紹
當走在東京的大街小巷時,在五花八門的廣告看板.雜誌.護照簽證.海關.宣傳品.廣告.旅遊和導覽手冊.產品包裝.甚至在餐廳菜單上,皆可看到上面有一組黑色神秘二維條碼圖案:QR Code,當看到有興趣的商品 ...
- DelphiXe5中的双向绑定(使用使用TBindScope和TBindExpression,并覆盖AfterConstruction函数)
在Delphi下等这一功能很久了,虽然C#下早已实现了这一功能.但是在Dephi下尝试这项功能时还是有些许的激动.闲言少絮,直接上代码. unit BindingDemo; interface use ...
- 《windows程序设计》学习_3.4:实现雷区翻转
#include<windows.h> #include "resource.h" LRESULT CALLBACK WndProc (HWND, UINT, WPAR ...
- DrawerLayout、CoordinatorLayout、CollapsingToolbarLayout的使用--AndroidSupportDesign练手
先po一张效果图 PS:原谅题主的懒惰吧.. 看着是不是很酷炫,那是因为5.0的动画做得好,代码其实没有多少,搞清楚这个布局的层次关系很重要. 废话不多说了,先来看布局文件 最外层是一个DrawerL ...
- C++ Primer 学习笔记_88_用于大型程序的工具 --异常处理[续1]
用于大型程序的工具 --异常处理[续1] 四.又一次抛出 有可能单个catch不能全然处理一个异常.在进行了一些校正行动之后,catch可能确定该异常必须由函数调用链中更上层的函数来处理,catch能 ...
- jquery表格可编辑修改表格里面的值,点击td变input无刷新更新表格
td点击后变为input可以输入,更新数据,无刷新更新 演示 XML/HTML Code <table border="0" cellpadding="0" ...
- java String分类trim,substring,replaceAll,indexOf使用功能
1.trim性能 特征去掉字符串首尾空格,防止不必要的空格导致错误. public class TrimTest { public static void main(String[] args) { ...
- C#中“走马灯”和类似“打地鼠”的小程序(Seventeenth Day)
今天主要复习了一下昨天学习的窗体小程序.主要会运用到控件的一些基本属性. 程序: 走马灯(要求是:使用两个窗体,两个窗体之间要传值,Form1传值给Form2,传入的字符串在Form2窗体上横向滚动) ...
- LINQ实现行列转换
用SQL语句实现行列转换很容易,但也有时候需要在程序中实现,找了好久,发现一篇文章写的挺不错的 http://blog.csdn.net/smartsmile2012/article/details/ ...