TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# StringBuilder Clear (Set Length to Zero)

Use the Clear method on the StringBuilder type. Test the Length of a StringBuilder.
Clear erases the character data from a StringBuilder instance. It is found in the .NET Framework 4.0. We can forget the data in the StringBuilder without allocating anything. This can lead to performance enhancements.StringBuilder
To start, this program appends ten digits to a StringBuilder. Then, it displays the Length of the buffer. Next, the Clear instance method is invoked, and finally the Length is displayed again: it is now zero.

Tip: Clear internally sets the Length of the StringBuilder to zero. It provides a "clearer" syntax for this operation.

C# program that demonstrates Clear method using System; using System.Text; class Program { static void Main() { var builder = new StringBuilder(); for (int i = 0; i < 10; i++) { builder.Append(i); } Console.WriteLine("Before Clear(): {0}", builder.Length); builder.Clear(); Console.WriteLine("After Clear(): {0}", builder.Length); } } Output Before Clear(): 10 After Clear(): 0
Internals. In the release notes for the .NET Framework 4.0, the Clear method is one of the new features. Out of interest, I opened the implementation in IL Disassembler. I found that Clear simply assigns the Length property to zero internally.

Note: The "return this" part means you can call another method chained after Clear() in the same statement.

ReturnThis

Tip: Other methods on the StringBuilder also return the StringBuilder reference. More examples of this pattern are available.

Summary. With the Clear method on the StringBuilder type, you have an efficient way of erasing the data stored inside the StringBuilder. It simply sets the Length property to zero internally. But this method is simpler than the Length property.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf