Saturday, 22 March 2014

How to define string array in c#

There is several ways to make the array of string, array of string means to just create the collection of strings.

1.       In C# programming string[] is used to create the collection of strings; reference can be null or assigned to a new string[]. Square brackets are used


@Code snippet for Creating Array of string in C# : C# Array
class Program
    {
        static void Main(string[] args)
        {
           
            string[] arr1 = new string[] { "String", "Array", "Values", "Display" }; // contain three values
            var arr3 = new string[] { "String", "Array", "Values", "Display" };
            string[] arr2 = { "String", "Array", "Values", "Display" };
            string[] arr4 = new string[4];
            arr4[0] = "String";
            arr4[1] = "Array";
            arr4[2] = "Values";
            arr4[3] = "Display";
            int count =1;
            foreach (string str in arr1)
            {
                Console.WriteLine(count + ". " + str);
                count++;
            }
        }
    }
@Output


2.       Creating the list of array and collection of string by List; List is a generic (constructed) type. You need to use < and > in the List declaration. List is the dynamic array type; you can remove insert or delete from any particular place in string array.
class Program
    {
        static void Main(string[] args)
        {
            //declaration 1 assing string one by one
            List<string> string2 = new List<string>();
            string2.Add("string");
            string2.Add("collection");
            string2.Add("test");
            //Declartion 2 - assign string at declartion time
            List<string> string1 = new List<string>(new string[] { "string","collection","test"});
            // Declartion 3 : assign array to string
            string[] arrString = new string[3];
            arrString[0] = "string";
            arrString[1] = "collection";
            arrString[2] = "test";
            List<string> list = new List<string>(arrString);
        
            int count =1;
            foreach (string str in string1)
            {
                Console.WriteLine(count + ". " + str);
                count++;
            }
        }
    }
@Output String List collection List

No comments:

Post a Comment

Others

You will like to read it