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的更多相关文章

  1. [翻译] GONMarkupParser

    GONMarkupParser https://github.com/nicolasgoutaland/GONMarkupParser NSString *inputText = @"Sim ...

  2. str_replace vs preg_replace

    转自:http://benchmarks.ro/2011/02/str_replace-vs-preg_replace/ 事实证明str_replace确实比preg_replace快. If you ...

  3. MySQL 中的 FOUND_ROWS() 与 ROW_COUNT() 函数

    移植sql server 的存储过程到mysql中,遇到了sql server中的: IF @@ROWCOUNT < 1 对应到mysql中可以使用 FOUND_ROWS() 函数来替换. 1. ...

  4. nodejs(三)Buffer module & Byte Order

    一.目录 ➤ Understanding why you need buffers in Node ➤ Creating a buffer from a string ➤ Converting a b ...

  5. Zend API:深入 PHP 内核

    Introduction Those who know don't talk. Those who talk don't know. Sometimes, PHP "as is" ...

  6. Java实现LeetCode_0020_ValidParentheses

    package javaLeetCode.primary; import java.util.Scanner; import java.util.Stack; public class ValidPa ...

  7. OSCP Learning Notes - Privilege Escalation

    Privilege Escalation Download the Basic-pentesting vitualmation from the following website: https:// ...

  8. 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 ...

  9. Exception (3) Java exception handling best practices

    List Never swallow the exception in catch block Declare the specific checked exceptions that your me ...

随机推荐

  1. codeforces 377B Preparing for the Contest 二分+优先队列

    题目链接 给你m个bug, 每个bug都有一个复杂度.n个人, 每个人有两个值, 一个是能力值, 当能力值>=bug的复杂度时才可以修复这个bug, 另一个是雇佣他需要的钱,掏一次钱就可以永久雇 ...

  2. ngrok原理浅析(转载)

    之前在进行 微信Demo开发时曾用到过 ngrok这个强大的tunnel(隧道)工具,ngrok在其github官方页面上的自我诠释是 "introspected tunnels to lo ...

  3. 关于BFC

    参考  http://www.html-js.com/article/1866(很棒! 还有栗子) http://www.cnblogs.com/lhb25/p/inside-block-format ...

  4. php基础知识笔记

    基本语法 php文件的后缀名可以是 .php .php3 .phtml 输出命令 echo , print 语句以;结束 注释 // /* */ 变量都带$前缀, 如: $x, $names, $th ...

  5. 转: Nodejs 发送HTTP POST请求实例

    项目里面需要用到使用NodeJs来转发HTTP POST请求,把过程记录一下: exports.sendEmail = function (req, res) { res.send(200, req. ...

  6. QListWidget的QComboBox下拉列表添加复选框及消息处理

    要在QComboBox下拉列表项中添加复选框,并进行消息处理,在网上搜索了很久没有找到太多有用的信息和实际的例子,但从中还是找到了一些提示性的资料,根据这些简短的介绍,最终实现了这个功能. QComb ...

  7. STL 全特化/偏特化

    template<class T> class Compare { public: static bool isEqual(const T& lh,const T& rh) ...

  8. 高级复制实验配置添加复制节点操作时报错:ORA-23308: object GP.T does not exist or is invalid

    出错原因: 使用高级复制时,在源端启动复制支持,执行语句:REPADMIN@bys1>execute dbms_repcat.generate_replication_support('gp', ...

  9. DrawerLayout、CoordinatorLayout、CollapsingToolbarLayout的使用--AndroidSupportDesign练手

    先po一张效果图 PS:原谅题主的懒惰吧.. 看着是不是很酷炫,那是因为5.0的动画做得好,代码其实没有多少,搞清楚这个布局的层次关系很重要. 废话不多说了,先来看布局文件 最外层是一个DrawerL ...

  10. SQL基础查询实战

    总结: 一.单表查询的情况: 1.where.....group by .. Having count(..) 2.Group by haing min(..)条件and max(..)条件(查询最低 ...