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 ...
随机推荐
- poj 2369 Permutations 置换
题目链接 给一个数列, 求这个数列置换成1, 2, 3....n需要多少次. 就是里面所有小的置换的长度的lcm. #include <iostream> #include <vec ...
- pl sql 无法解析指定的连接标识符
使用PLSQL Developer时,“ORA-12154: TNS:无法解析指定的连接标识符”问题的一个解决办法< xmlnamespace prefix ="o" ...
- Html 小插件2
调用google的JS翻译插件实现页面自动翻译功能 网址http://translate.google.com/translate_tools 设置自己需要的配置生成如下代码放到自己站的页面头部 代码 ...
- java MemCachedClient遍历memcache中所有的key
在java memcached client documentation中没有提共遍历memcache所有key的方法.但是提供了两个方法statsItems和statsCacheDump,通过sta ...
- c++11新特性(4) lambda捕捉块
lambda表达式中的方括号成为捕捉块,能够在这里指定怎样从所在的作用域中捕捉变量. 捕捉的意思是指能够在该lambda中使用该变量.即能够捕获外部变量在lambda表达式内使用. 能够使用两种方式来 ...
- hdu 4738 Caocao's Bridges(2013杭州网络赛丶神坑)
就是求最小权值的桥..不过有好几个坑... 1:原图不连通,ans=0. 2: m<=n^2 显然有重边,重边必然不是桥,处理重边直接add(u, v, INF). 3: 最小桥边权为0的时 ...
- UIGI 一级二级三级四级啦啦啦等列表层式排列效果
在每个需要排序的物体上放入GridTag 脚本 其中GridTag脚本用于提供此物体的深度 using UnityEngine; using System.Collections; using Uni ...
- bzoj 1040: [ZJOI2008]骑士 树形dp
题目链接 1040: [ZJOI2008]骑士 Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 3054 Solved: 1162[Submit][S ...
- rhApp遇到的项目问题
1.如果有多人同时操作一个桌台的情况下,如何处理: 2.index页面点击清空的时候是否要把桌台一起清掉: 3.账单界面已结账的小单背景色是否需要和未结账的不同:
- QT小技巧—更好管理项目(增加预编译头文件,并且指定moc文件的生成位置)good
预编译加速编译 QT也可以像VS那样使用预编译头文件来加速编译器的编译速度.首先在.pro文件中加入: CONFIG += precompiled_header 然后定义需要预编译的头文件: PREC ...