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 ...
随机推荐
- JS笔记 入门第四
小测试: 注意:取消所有的设定可以直接使用 document.getElementById("txt").removeAttribute("style"); 这 ...
- python爬虫数据抓取方法汇总
概要:利用python进行web数据抓取方法和实现. 1.python进行网页数据抓取有两种方式:一种是直接依据url链接来拼接使用get方法得到内容,一种是构建post请求改变对应参数来获得web返 ...
- ObjectiveC 文件操作一
1,引用和使用文件 NSFileManager 是一个单例对象,在mac应用中可以获取任何地址,在IOS中获取的是相对应的应用程序的地址.可以使用 defaultManager 来得到当前应用程序地址 ...
- 编程实现Windows系统自动登录
编程实现Windows系统自动登录 原理: 通过注册表修改实现.Windows内置了自动登录的机制,在登录系统时,winlogon会检查注册表下有没有设置自动登录,如果设置了就上就会读取用户名和密码, ...
- Leetcode OJ 刷题
Valid Palindrome吐槽一下Leetcode上各种不定义标准的输入输出(只是面试时起码能够问一下输入输出格式...),此篇文章不是详细的题解,是自己刷LeetCode的一个笔记吧,尽管没有 ...
- ShineTime 是一个效果非常精致的缩略图相册
ShineTime 是一个效果非常精致的缩略图相册,鼠标悬停到缩略图的时候有很炫的闪光效果,基于 CSS3 实现,另外缩略图也会有立体移动的效果.特别适用于个人摄影作品,公司产品展示等用途,快来来围观 ...
- OpenCV 开发环境环境搭建(win10+vs2015+opencv 3.0)
OpenCV 3.0 for windows(下载地址:http://opencv.org/): 本测试中,OpenCV安装目录:D:\Program Files\opencv,笔者操作系统为64位. ...
- 【转】sqlserver数据库之间的表的复制
以下以数据库t1和test为例. 1.复制表结构及资料 select * into 数据库名.dbo.表名 from 源表(全部数据) 如:select * into t1.dbo.YS1 ...
- JavaSE复习日记 : 循环语句(for/while/do while)
/* * 循环语句(for循环,while和do while循环) */ /* * for循环语句 * * for循环语法: * for (表达式1;表达式2;表达式3 ){ * java语句 * } ...
- Protel99se教程四:将SCH转为PCB文件
本节课,我们介绍,如何快速的将绘制好的SCH文件转为PCB文件,首先,我们打开刚开始时我们绘制的SCH原理图,我们可以使用protel99se菜单栏的view-Fit All Objects命令,以查 ...