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 ...
随机推荐
- codeforces 292E. Copying Data 线段树
题目链接 给两个长度为n的数组, 两种操作. 第一种, 给出x, y, k, 将a[x, x+k-1]这一段复制到b[y, y+k-1]. 第二种, 给出x, 输出b[x]的值. 线段树区间更新单点查 ...
- 批处理[Batch]
批处理 1. 定义:就是一堆DOS命令按一定顺序排列而形成的集合. 英文译为BATCH,批处理文件后缀BAT就取的前三个字母. 示例1:a.bat @echo off Netstat –a –n &g ...
- HDU 1076 An Easy Task
题解:枚举即可…… #include <cstdio> int main(){ int now,y,n,T,count; scanf("%d",&T); whi ...
- php抽象类和接口
接口 使用接口,你可以指定某个类必须实现那些方法,但是不需要定义这些方法的具体内容,我们可以通过interface来定义一个接口,就像定义标准类一样,但其中定义所有的方法都是空的,接口中定义的所有的方 ...
- distributor之Interrupt Set/Clear-Active Registers, GICD_IS/CACTIVERn
set active寄存器.顾名思义就是把一个中断置为active状态,clear active寄存器就是清除active状态,在这里我们有必要说明一下中断状态的一些概念: active状态:假设此时 ...
- android解决内存溢出的问题(没有从根本上解决)
Android游戏虚拟机算法JNI 尽量不要使用setImageBitmap或setImageResource或BitmapFactory.decodeResource来设置一张大图,因为这些函数在完 ...
- STL中主要的算法(一)
一.replace() 替换算法将指定元素值替换为新值,使用原型例如以下,将迭代器[first,last)中值为old_value的元素所有替换为new_value值. 函数原型: template ...
- js 时间戳转换成时间格式,可自定义格式
由于 c# 通过ajax获取的时间 传到前台 格式为:/Date(1354116249000)/ 所以需要转换一下,想要什么格式 更改 format() 里的 返回语句 就可以了 formatDate ...
- 常用上网增强类Chrome扩展(转)
Chrome是个非常好用的浏览器,拥有丰富的扩展资源库,能够满足网民各种各样的需求,对于网民来说,通过Chrome扩展来增强上网体验是一个基本需求,但是安装过多的扩展有容易耗费大量系统资源,今天月光博 ...
- Immediate Decodability问题Java解答
DescriptionAn encoding of a set of symbols is said to be immediately decodable if no code for one sy ...