Skip to main content
Published on

More About Strings in C#

Share:

Introduction

In the world of C# programming, strings play a fundamental role. In this article, we will explore aspects beyond the basics, diving into advanced manipulations and powerful string features.

String Fundamentals

A string in C# is a collection of characters and is treated as an object. Below are some basic and advanced string features in C#.

Special Characters and Escape Sequences

  • \n: New line.
  • \t: Tab.

Essential Properties and Methods

  • variable.Length: Returns the length of the string.
  • variable.ToUpper() and variable.ToLower(): Case transformation.

Comparing Strings

String comparison is a critical operation in many applications. C# offers methods for comparing strings effectively:

  • String.Equals(): Compares two strings in a case-sensitive and culture-sensitive manner.
  • String.Compare(): A more flexible form that allows case-insensitive comparisons.

Formatting and Interpolation

Formatting is crucial for displaying data in a readable way. C# provides several ways to format strings:

  • String.Format(): Allows the creation of formatted strings.
  • String Interpolation: A more modern and readable way to format strings, using $"Text {variable}".

Code Example

using System;

namespace Base {
  class MoreAboutStrings {
    public void Run() {
      string firstName = "Nelson";
      string lastName = "Silva";
      int age = 28;

      // Concatenation and interpolation
      string message = $"Name: {firstName} {lastName}, Age: {age}";

      // Using comparison methods
      if (firstName.Equals("Nelson")) {
        Console.WriteLine("Name verified successfully!");
      }

      // String formatting
      string info = String.Format("Name: {0} {1}, Age: {2}", firstName, lastName, age);
      Console.WriteLine(info);
    }
  }
}

Conclusion

Mastering strings in C# is vital for effective and productive development. From basic manipulation to comparison and formatting techniques, understanding strings helps create clearer and more efficient code.

Happy coding!