What is character array in C#, explain with an example?

Learn, what is character array, how it is declared, used within a C# program?
[Last updated : March 19, 2023]

C# - Character Array

In C and C++ programming language, string is used as a character array.

But in C#, string and character array both are independent type. Some pre-defined methods are used to convert each other.

In character array, we can access each character individually. But in case of string we need to use substring method.

Initialization of character array

char []ch = { '1','2','3','4','5'};
char[] ch1 = "Hello"; //This is an error in c#

Character Array Example in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            char[] ch = { 'A', 'B', 'C', 'D', 'E' };
            char[] ch1 = new char[5];

            int i = 0;

            ch1[0] = 'a';
            ch1[1] = 'b';
            ch1[2] = 'c';
            ch1[3] = 'd';
            ch1[4] = 'e';

            Console.WriteLine("First array: ");
            for (i = 0; i < ch.Length; i++)
            {
                Console.Write(ch[i] + "");
            }

            Console.WriteLine("\nSecond array: ");
            for (i = 0; i < ch.Length; i++)
            {
                Console.Write(ch1[i] + "");
            }

            Console.WriteLine();
        }
    }
}

Output

First array:
ABCDE
Second array:
abcde

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.