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 ...
随机推荐
- MySQL Select 优化
准备: create table t(x int primary key,y int unique,z int); insert into t(x,y,z) values(1,1,1),(2,2,2) ...
- Dijkstra算法模拟讲解
dijkstra算法,是一个求单源最短路径算法 其算法的特点为: 层层逼进,有点类似宽度搜索的感觉 其需要的数据结构为: int map[N][N] 所有点之间的权表 ...
- 宣布发布全新的 Windows Azure 缓存预览版
全新 Windows Azure 缓存的预览版现已发布.此托管服务可以提供闪电般的数据访问速度,以帮助您构建更具可伸缩性.响应更快的应用程序. 详情如下: · 托管式缓存:这一全新的托管服务为需 ...
- Juicy Couture_百度百科
Juicy Couture_百度百科 Juicy Couture
- c#中常用的异常类型
c#中异常捕获catch{}常用的异常类型 Exception 类 描述 SystemException 其他用户可处理的异常的基本类 ArgumentException 方法的参数是非法的 ...
- 一、Cocos2dx在visualStudio或者vc++中环境搭建(入门篇)
本文由qinning199原创,转载请注明:http://www.cocos2dx.net/?p=106 0.概述 Cocos2dx-win32的项目能够被向导生成 向导支持vs2008,vs2010 ...
- HDU3853-LOOPS(概率DP求期望)
LOOPS Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 125536/65536 K (Java/Others) Total Su ...
- OpenStack里的浮动ip
缺省情况下实例会被赋予固定ip,这时并不能保证实例会马上可以从外面访问到,一般来说需要配置防火墙来允许公共ip,然后建立一条NAT规则从公共ip到私有ip的映射.OpenStack引入了一个叫浮动ip ...
- SQL修炼道路上必看的书籍
1 SQL应用重构 9787111263586 2 SQL 必知必会(第3版) 9787115162601 3 SQL Server 2005高级程序设计 9787115170798 4 SQL 解惑 ...
- BZOJ 1602: [Usaco2008 Oct]牧场行走( 最短路 )
一棵树..或许用LCA比较好吧...但是我懒...写了个dijkstra也过了.. ---------------------------------------------------------- ...