OneBite.Dev - Coding blog in a bite size

Convert An Array To A String In C#

Code snippet for how to Convert An Array To A String In C# with sample and detail explanation

C# is a programming language that provides an array of techniques for different purposes, but sometimes the implementation can be tricky for beginners. In this article we will discuss how to convert an array to a string in C#, providing a simple code snippet and a step-by-step explanation that’s easy to follow.

Code snippet: Converting an array to a string in C#

using System;

class Program {
    static void Main() {
        int[] array = {1, 2, 3, 4, 5};
        string result = String.Join(", ", array);
        Console.WriteLine(result);
    }
}

Code Explanation: Converting an array to a string in C#

First, we import the necessary namespace for our program, System.

using System;

Next in our Main function, we declare and initialize an integer array by the name array.

int[] array = {1, 2, 3, 4, 5};

Following that, we use the String.Join method to convert our array to a string. The Join method takes two parameters: the first is the separator that you want to use (in this case, a comma followed by a space), and the second is the array that you want to convert.

string result = String.Join(", ", array);

After we’ve converted our array to a string, we print out the result to the console using the Console.WriteLine method.

Console.WriteLine(result);

When we run this program, it will output:

1, 2, 3, 4, 5

This is our array, now converted into a string! With this simple code snippet, you can easily turn any array into a string in C#. This feature can come in handy in many situations, especially when you want to display the values of an array in a user-friendly format.

c-sharp