Open In App

C# | Arrays of Strings

Last Updated : 19 Nov, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

An array is a collection of the same type variable. Whereas a string is a sequence of Unicode characters or array of characters. Therefore arrays of strings is an array of arrays of characters. Here, string array and arrays of strings both are same term.

For Example, if you want to store the name of students of a class then you can use the arrays of strings. Arrays of strings can be one dimensional or multidimensional.

Declaring the string array: There are two ways to declare the arrays of strings as follows

  • Declaration without size:

    Syntax:

    String[] variable_name;

    or

    string[] variable_name;

  • Declaration with size:

    Syntax:

    String[] variable_name = new String[provide_size_here];

    or

    string[] variable_name = new string[provide_size_here];

Example:

// declaration using string keyword
string[] s1;

// declaration using String class object
// by giving its size 4
String[] s2 = new String[4];

Initialization of Arrays of Strings: Arrays can be initialized after the declaration. It is not necessary to declare and initialize at the same time using the new keyword. However, Initializing an Array after the declaration, it must be initialized with the new keyword. It can’t be initialized by only assigning values.

Example:

// Declaration of the array
string[] str1, str2;

// Initialization of array
str1 = new string[5]{ “Element 1”, “Element 2”, “Element 3”, “Element 4”, “Element 5” };

str2 = new string[]{ “Element 1”, “Element 2”, “Element 3”, “Element 4”, “Element 5” };

Note: Initialization without giving size is not valid in C#. It will give compile time error.

Example: Wrong Declaration for initializing an array

// compile-time error: must give size of an array
String[] str = new String[];

// error : wrong initialization of an array
string[] str1;
str1 = {“Element 1”, “Element 2”, “Element 3”, “Element 4” };

Accessing Arrays of Strings Elements: At the time of initialization, we can assign the value. But, we can also assign the value of array using its index randomly after the declaration and initialization. We can access an array value through indexing, placed index of the element within square brackets with the array name.

Example:

// declares & initializes string array
String[] s1 = new String[2];

// assign the value "Geeks" in array on its index 0
s1[0] = 10; 

// assign the value "GFG" in array on its index 1
s1[1] = 30;

// assign the value "Noida" in array on its index 2
s1[2] = 20;


// Accessing array elements using index
s1[0];  // returns Geeks
s1[2];  // returns Noida

Declaration and initialization of string array in a single line: String array can also be declared and initialized in a single line. This method is more recommended as it reduces the line of code.

Example:

String[] weekDays = new string[3] {"Sun", "Mon", "Tue", "Wed"}; 

Code#1: String array declaration, initialization and accessing its elements




// C# program to illustrate the String array 
// declaration, initialization and accessing 
// its elements
using System;
  
class Geeks {
      
    // Main Method
    public static void Main()
    {
        // Step 1: Array Declaration
        string[] stringarr; 
          
        // Step 2:Array Initialization
        stringarr = new string[3] {"Element 1", "Element 2", "Element 3"}; 
          
        // Step 3:Accessing Array Elements
        Console.WriteLine(stringarr[0]); 
        Console.WriteLine(stringarr[1]); 
        Console.WriteLine(stringarr[2]); 
    }
}


Output:

Element 1
Element 2
Element 3

Code#2: Array declaration and initialization in single line




// C# code to illustrate Array declaration
// and initialization in single line
using System;
  
class Geeks {
  
    // Main Method
    public static void Main()
    {
        // array initialization and declaration
        String[] stringarr = new String[] {"Geeks", "GFG", "Noida"}; 
  
        // accessing array elements
        Console.WriteLine(stringarr[0]);
        Console.WriteLine(stringarr[1]);
        Console.WriteLine(stringarr[2]);
    }
}


Output:

Geeks
GFG
Noida

Note:

  • In the public static void main(String[] args), String[] args is also an array of string.

    Example: To show String[] args is an array of string.




    // C# program to get the type of "args"
    using System;
      
    class GFG {
      
        // Main Method
        static public void Main (String[] args) {
              
            // using GetType() method to
            // get type at runtime
            Console.WriteLine(args.GetType());
        }
    }

    
    

    Output:

    System.String[]
    
  • C# string array is basically an array of objects.
  • It doesn’t matter whether you are creating an array of string using string keyword or String class object. Both are same.

    Example:




    // C# program to get the type of arrays of 
    // strings which are declared using 'string'
    // keyword and 'String class object'
    using System;
      
    class GFG {
      
        // Main Method
        static public void Main (String[] args) {
      
            // declaring array of string 
            // using string keyword
            string[] s1 = {"GFG", "Noida"};
      
             // declaring array of string 
            // using String class object
            String[] s2 = new String[2]{"Geeks", "C#"};
      
            // using GetType() method to
            // get type at runtime
            Console.WriteLine(s1.GetType());
            Console.WriteLine(s2.GetType());
        }
    }

    
    

    Output:

    System.String[]
    System.String[]
    


Similar Reads

C# | Arrays
An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array specifies the number of elements present in the array
13 min read
C# | Using foreach loop in arrays
C# language provides several techniques to read a collection of items. One of which is foreach loop. The foreach loop provides a simple, clean way to iterate through the elements of an collection or an array of items. One thing we must know that before using foreach loop we must declare the array or the collections in the program. Because the forea
4 min read
Passing arrays as arguments in C#
An array is a collection of similar type variables which are referred to by a common name. In C#, arrays are the reference types so it can be passed as arguments to the method. A method can modify the value of the elements of the array. Both single-dimensional and multidimensional arrays can be passed as an argument to the methods. Passing 1-D Arra
4 min read
C# | Implicitly Typed Arrays
Implicitly typed arrays are those arrays in which the type of the array is deduced from the element specified in the array initializer. The implicitly typed arrays are similar to implicitly typed variable. In general, implicitly typed arrays are used in the query expression.Important points about implicitly typed arrays: In C#, the implicitly typed
3 min read
How to Combine Two Arrays without Duplicate values in C#?
Given two arrays, now our task is to merge or combine these arrays into a single array without duplicate values. So we can do this task using the Union() method. This method combines two arrays by removing duplicated elements in both arrays. If two same elements are there in an array, then it will take the element only once. Syntax: first_array.Uni
3 min read
C# | Jagged Arrays
Prerequisite: Arrays in C#Jagged array is a array of arrays such that member arrays can be of different sizes. In other words, the length of each array index can differ. The elements of Jagged Array are reference types and initialized to null by default. Jagged Array can also be mixed with multidimensional arrays. Here, the number of rows will be f
5 min read
C# | How to use strings in switch statement
The switch statement is a multiway branch statement. It provides an easy way to forward execution to different parts of code based on the value of the expression. String is the only non-integer type which can be used in switch statement. Important points: Switching on strings can be more costly in term of execution than switching on primitive data
2 min read
C# | Get the number of strings in StringCollection
StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace. StringCollection.Count property is used to get the number of strings contained in the StringCollection. Syntax: public int Count { get; } Return Valu
2 min read
C# | Remove all the strings from the StringCollection
StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace. StringCollection.Clear method is used to remove all the strings from the StringCollection. Syntax: public void Clear (); Note: Count is set to zero,
2 min read
Interpolated Verbatim Strings in C# 8.0
Prerequisite: String Interpolation and Verbatim String Before C# 8.0 you are allowed to use string interpolation($) and verbatim identifier(@) together but in a specific sequence. It means when you use $ token and @ token together, it is necessary that $ token must appear before the @ token. If you use the @ token before $ token, then the compiler
3 min read
C# Program to Check Given Strings are Equal or Not Using equal to (==) Operator
Given two strings we need to check if they are equal by using the == operator. The == Operator compares the reference identity i.e. whether they are referring to the same identity in the heap. If they are equal then it will return true, otherwise, return false. Example: Input String 1 : geeks String 2 : geeks Output : Equal Input String 1 : geeks S
2 min read
C# - Randomly Generating Strings
In C#, a string is a sequence of Unicode characters or an array of characters. The range of Unicode characters will be U+0000 to U+FFFF. A string is the representation of the text. In this article, we will learn how to randomly generate strings and alphanumeric strings. So to do the task we use the Random class although it generates integers we can
6 min read
How to Compare Strings in C#?
A string is a collection of characters and is used to store plain text. Unlike C or C++, a string in C# is not terminated with a null character. The maximum size of a string object depends on the internal architecture of the system. A variable declared followed by "string" is actually an object of string class. How to instantiate a string object?We
13 min read
C# Tutorial
In this C# (C Sharp) tutorial, whether you’re beginner or have experience with other programming languages, our free C# tutorials covers the basic and advanced concepts of C# including fundamentals of C#, including syntax, data types, control structures, classes, and objects. You will also dive into more advanced topics like exception handling, and
8 min read
ASP.NET Interview Questions and Answer
ASP.NET is a powerful framework for building dynamic web applications, known for its scalability, performance, and integration with the .NET ecosystem, developed by Microsoft that allows developers to build dynamic web applications, websites, and services. It is part of the larger .NET framework and provides a comprehensive programming model for cr
15+ min read
C# Interview Questions and Answers
C# is the most popular general-purpose programming language and was developed by Microsoft in 2000, renowned for its robustness, flexibility, and extensive application range. It is simple and has an object-oriented programming concept that can be used for creating different types of applications. Here, we will provide 50+ C# Interview Questions and
15+ min read
Program to calculate Electricity Bill
Given an integer U denoting the amount of KWh units of electricity consumed, the task is to calculate the electricity bill with the help of the below charges: 1 to 100 units - [Tex]Rs. 10/unit[/Tex]100 to 200 units - [Tex]Rs. 15/unit[/Tex]200 to 300 units - [Tex]Rs. 20/unit[/Tex]above 300 units - [Tex]Rs. 25/unit[/Tex] Examples: Input: U = 250 Outp
9 min read
HashSet in C# with Examples
In C#, HashSet is an unordered collection of unique elements. This collection is introduced in .NET 3.5. It supports the implementation of sets and uses the hash table for storage. This collection is of the generic type collection and it is defined under System.Collections.Generic namespace. It is generally used when we want to prevent duplicate el
6 min read
C# Dictionary with examples
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.Collections.Generic namespace. It is dynamic in nature means the size of the dictionary is growing
5 min read
Difference between Abstract Class and Interface in C#
An abstract class is a way to achieve abstraction in C#. To declare an abstract class, we use the abstract keyword. An Abstract class is never intended to be instantiated directly. This class must contain at least one abstract method, which is marked by the keyword or modifier abstract in the class definition. The Abstract classes are typically use
4 min read
C# | Arrays of Strings
An array is a collection of the same type variable. Whereas a string is a sequence of Unicode characters or array of characters. Therefore arrays of strings is an array of arrays of characters. Here, string array and arrays of strings both are same term. For Example, if you want to store the name of students of a class then you can use the arrays o
4 min read
Introduction to .NET Framework
The .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The framework includes a variety of programming languages, such as C#, F#, and Visual Basic, and supports a range of application types,
7 min read
Common Language Runtime (CLR) in C#
The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others. When a C# program is compiled, the resulting executable code is in an intermediate
6 min read
C# | List Class
List<T> class represents the list of objects which can be accessed by index. It comes under the System.Collections.Generic namespace. List class can be used to create a collection of different types like integers, strings etc. List<T> class also provides the methods to search, sort, and manipulate lists. Characteristics: It is different
6 min read
C# | Encapsulation
Encapsulation is defined as the wrapping up of data and information under a single unit. It is the mechanism that binds together the data and the functions that manipulate them. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield. Technically in encapsulation, the varia
5 min read
C# | Method Overriding
Method Overriding in C# is similar to the virtual function in C++. Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class. Creating a method in the derived class with the same signature as a method in the base class is called as method overriding. In simple words, Overriding is a
8 min read
C# | Delegates
A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered. For example, if you click on a Button on a form (Windows Form a
6 min read
C# | Inheritance
Introduction: Inheritance is a fundamental concept in object-oriented programming that allows us to define a new class based on an existing class. The new class inherits the properties and methods of the existing class and can also add new properties and methods of its own. Inheritance promotes code reuse, simplifies code maintenance, and improves
7 min read
C# | Generics - Introduction
Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces. A primary limitation of collections is the abs
6 min read
C# | Data Types
Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C#, each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data type
7 min read
Article Tags :