C# - String Object


In C#, a string is a sequence of characters that is used to represents text. Strings are reference types, which means they are allocated on the heap and can be null. They are also called immutable, which means that once a string is created, its contents cannot be changed.

C# String object

Here is an example of a string in C#:

string message = "TutorialsTrend!";

In this example, the message variable is assigned the value "TutorialsTrend!" using a string literal. String literals are enclosed in double quotes and can contain any combination of characters, including whitespace, punctuation, and special characters.

Strings in C# have a number of built-in methods that allow you to manipulate and format them. Here are a few examples.

 string name = "Rohatash";
int age = 35;
int length = name.Length;
string upperCaseName = name.ToUpper();
string formattedString = string.Format("My name is {0} and I am {1} years old.", name, age); 

In the above example, the Length property returns the number of characters in the string, the ToUpper() method returns a new string with all characters converted to uppercase, and the Format() method allows you to construct a formatted string using placeholders ({0}, {1}, etc.) that are replaced with the corresponding arguments.

1. String Length

A string in C# is actually an object, which contain properties and methods that can perform certain operations on strings. For example, the length of a string can be found with the Length property.

string name = "Rohatash";
int length = name.Length;           

2. ToUpper() and ToLower() Mehods

ToUpper() and ToLower() are used to returns a copy of the string converted to uppercase or lowercase.

string name = "Rohatash";
int length = name.Length;
string upperCaseName = name.ToUpper();
string lowerCaseName = name.ToLower();   

Other string methods you can also use. The is the example of length propertiy and upper and lower method.

Example

using System;

namespace FirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "Rohatash";
            int age = 35;
            int length = name.Length;
            string upperCaseName = name.ToUpper();
            string formattedString = string.Format("My name is {0} and I am {1} years old.", name, age); 
            Console.WriteLine("Name Length is : " + length);
            Console.WriteLine("Name uppercase is : " + upperCaseName);
            Console.WriteLine("String Format is : "+formattedString);
        }       
    }
}

Output

C# String object
Prev Next