Sponsored Ad

Monday, May 14, 2012

Example to Use String as an Array in C#

At some places you can use the C# string as a C# array. you can print the particular char from a string by giving the index of array. but you can not change the value of a char inside the string.

strSample[6] = 'n';

The above operation is not allowed.  you can use the ToCharArray function to convert the string to char array and use in foreach loop also.

Example to Use String as an Array in C#

using System;

namespace CSharpLab
{
    class Programs
    {       
        static void Main(string[] args)
            {
                string strSample = "This is C# Example Blog.";
            Console.WriteLine(strSample);
            //not allowed
            //strSample[6] = 'n';
            Console.WriteLine(strSample[9]);

            foreach(char ch in strSample.ToCharArray())
                Console.Write(ch);
                Console.ReadLine();
            }
    }   
}

Sunday, May 6, 2012

How to Initialize Constant Data Type in C#

You can assign the constant data type at the tome of defining it only. If you will try to modify the const datatype later during the program it will through a error.

using System;

namespace ConsoleLab
{
    class Programs
    {
        static void Main(string[] args)
        {
            //initilize constant data type while defining it.
            const int CsharpConst = 0;

            //Const Error - The left-hand side of an assignment must be a variable, property or indexer
            //CsharpConst = 5;
            Console.ReadLine();
        }
    }
}

Terminate the Program Execution and Exit in C#

C# provide a environment level method to exit from the current execution and give control to OS. The below code snippet demonstrate the C# functionality to terminate a program.

Terminate the Program Execution and Exit in C#

using System;

namespace ConsoleLab
{
    class Programs
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Press Any Key to Close the Window and Exit from Program Execution...");
            Console.ReadLine();

            Environment.Exit(-1);
            Console.ReadLine();
        }
    }
}

Development Updates