C# Introduction

Life is 10% what happens to us and 90% how we react to it. If you don't build your dream, someone else will hire you to help them build theirs.

C# Introduction

C# Statements – Basic Programming

There are various basic things in C# that you need to know. These are very small but too effective. These are called statements in C#. Without covering statements in C#, you can’t be a good programmer.
In C# programming, there is various statements as block, empty, goto-label, break, continue, return, throw, checked, unchecked, lock, using etc. These are small but give powerful control you to write your program.

C# Block Statement({})

The block statement is used to write multiple segments of program in logical group.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace run_csharp_code
{ //Begin Statement
    class Program
    { // Begin Statement
        static void Main(string[] args)
        { //Begin Statement
            int num1, power;
            num1 = 5;
            power = num1 * num1;
            Console.WriteLine(power);
            Console.ReadLine();
        } // End Statement
    } // End Statement
} // End Statement
C# Empty Statement(;)

Empty statement is used when you no need to perform an operation where a statement is required. It simple transfers control to the end point of the statement. It is also very useful with while loop with blank body and label statements.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace empty_statements
{
    class Program
    {
        public bool print()
        {
            Console.WriteLine("Steven Clark");
            return true;
        }
        static void Main(string[] args)
        {
            int i = 0;
            Program p = new Program();
            while (p.print())
            {
                ; //Empty Statement
            }
            Console.WriteLine("i = {0}", i);
            Console.ReadLine();
        }
    }
}

Note: It processes infinite loop so terminating the program press ctrl+c.

C# Goto Statement

The goto statement is a jump statement that controls the execution of the program to another segment of the same program. You create label at anywhere in program then can pass the execution control via the goto statements.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace goto_statements
{
    class Program
    {
        static void Main(string[] args)
        {
            string name;
 
        label: //creating label with colon(:)
 
            Console.WriteLine("Enter your name: ");
            name = Console.ReadLine();
 
            Console.WriteLine("Welcome {0}", name);
            Console.WriteLine("Press Ctrl + C for Exit\n");
 
            goto label; //jump to label statement           
        }
    }
}

Note: To terminate the program press Ctrl+C

C# Break Statement

The break statement is used to terminating the current flow of program and transfer controls to the next execution.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace break_statements
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
 
            while (i < 100)
            {
                Console.WriteLine(i);
                if (i == 20)
                {
                    Console.WriteLine("breaking the current segment...");
                    break;
                }
                i++;
            }
            Console.ReadLine();
        }
    }
}
C# Continue Statement

The continue statements enables you to skip the loop and jump the loop to next iteration.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace continue_statements
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            while (i < 10)
            {
                i++;
                if (i < 6)
                {
                    continue;
                }
                Console.WriteLine(i);
            }
            Console.ReadLine();
        }
    }
}

In this program, skips the loop until the current value of i reaches 6.

C# Return Statement

A return statement is used for returning value to the caller from the called function. A easy example is mentioned below in a program that demonstrate the return statement very clearly.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace return_statements
{
    class Program
    {
        public int add(int num1, int num2)
        {
            // returns the add of num1 and num2
            return num1 + num2;
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            int result;
            // calling the function add that will return 9 to the result vaiable.
            result = p.add(3, 6);
            Console.WriteLine(result);
 
            Console.ReadLine();
        }
    }
}

In this example the variable result calls the function add() with two parameters and the function add() returns addition of both number to the result variable using return keyword.

C# Throw Statement

Throw statement is used for throwing exception in a program. The throwing exception is handled by catch block. You will learn complete about throw statement in Exception handling tutorial.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace throw_statement
{
    class Program
    {
        static void Main(string[] args)
        {
            int num1, num2, result;
 
            Console.WriteLine("Enter First Number");
            num1 = Convert.ToInt32(Console.ReadLine());
 
            Console.WriteLine("Enter Second Number");
            num2 = Convert.ToInt32(Console.ReadLine());
 
            try
            {
                if (num2 == 0)
                {
                    throw new Exception("Can’t Divide by Zero Exception\n\n");
                }
                result = num1 / num2;
                Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error : " + e.ToString());
            }
            Console.ReadLine();
        }
    }
}

When you will execute this code, and input 0 for second input then you will get the Can’t Divide by Zero Exception that is raised by throw statements.

C# Checked Statement

The checked statements force C# to raise exception whenever underflow or stack overflow exception occurs due to integral type arithmetic or conversion issues.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Checked_Statement
{
    class Program
    {
        static void Main(string[] args)
        {
            int num;
            // assign maximum value
            num = int.MaxValue;
            try
            {
                checked
                {
                    // forces stack overflow exception
                    num = num + 1;
                    Console.WriteLine(num);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.ReadLine();
        }
    }
}

This program raises exception while executing because it is using checked statement that prevent the current execution when stack overflow exception appears.

C# Unchecked Statement

The unchecked statement ignores the stack overflow exception and executes the program so, the output can be incorrect.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Unchecked_Statement
{
    class Program
    {
        static void Main(string[] args)
        {
            int num;
            // assign maximum value
            num = int.MaxValue;
            try
            {
                unchecked
                {
                    // forces stack overflow exception
                    num = num + 1;
                    Console.WriteLine(num);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.ReadLine();
        }
    }
}

Here, the correct output should be 2147483648 but the output is -2147483648 which is wrong because of unchecked statements as it ignores exception and put output on screen.

C# Lock Statement

The lock statement handle lock segment as a critical section and lock the object during the execution of program from other thread. Once the execution is completed it releases the lock and frees objects.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Lock_Statement
{
    class Program
    {
        public void printname()
        {
            Console.WriteLine("My name is Steven Clark");
        }
 
        static void Main(string[] args)
        {
            Program p = new Program();
            // creating lock segment. all the resources that is used in lock segment, can't be used by another thread until it releases.
            lock (p)
            {
                p.printname();
            }
            Console.ReadLine();
        }
    }
}
C# Using Statement

The using statement is mostly used when you need to one or more resources in a segment. The using statement obtains one or various resources, executes them and then releases the objects or resources. It is widely used in database connectivity through C#.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Using_Statement
{
    class check_using : IDisposable
    {
        public void Dispose()
        {
            Console.WriteLine("Execute  Second");
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            using (check_using c = new check_using())
            {
                Console.WriteLine("Executes First");
            }
            Console.WriteLine("Execute Third");
            Console.ReadLine();
        }
    }
}

In the above example, the using statement calling the check_using class to execute. So, it first executes the using block, then executes the check_using class and finally executes the last statements.

C# Enumeration

Enumeration provides efficient way to assign multiple constant integral values to a single variable. Enumeration improves code clarity and makes program easier to maintain. Enumeration in C# also provides more security by better error-checking technology and compiler warnings.
An enumeration can be defined using enum keyword. In enumeration, you can define special set of value that can be assigned with enumeration. For Example, you are creating an attendance log application in which a variable can contains value only Monday to Friday. The other value will not be applicable with variables. In order to fulfill this requirement you need to use enumeration that will hold only assigned values and will returns numeric position of values starting with zero.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Enumeration
{
    // creating enumeration for storing day.
    public enum attandance
    {
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            attandance present = attandance.Monday;//Valid
            Console.WriteLine(present);
 
            //attandance absent = attandance.Sunday;//Invalid
            Console.ReadLine();
        }
    }
}

In the preceding example, we created attendance enumeration in which 5 values are assigned as Monday, Tuesday, Wednesday, Thursday and Friday. Only these 5 values are valid entry for attendance enumeration variable. If you assign other entry as Sunday or Saturday, it will be invalid and you will get compile time error in C# programming.

Structure (C#)

Structure is the value type data type that can contain variables, methods, properties, events and so on. It simplifies the program and enhance performance of code in C# programming.
The structure encapsulate small group of related variables inside a single user-defined data type. It improves speed and memory usage and also enhances performance and clarity of your code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Structure_Statements
{
    class Program
    {
        // creating three different variable in single structure
        struct book
        {
            public string bookname;
            public int price;
            public string category;
        }
 
        static void Main(string[] args)
        {
            //Creating two book type variable
            book language, database;
 
            // Storing value in language variable
            Console.Write("Enter book name:\t");
            language.bookname = Console.ReadLine();
            Console.Write("Enter book price:\t");
            language.price = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter book category:\t");
            language.category = Console.ReadLine();
 
            //Storing value in database variable
            Console.Write("\n\nEnter book name:\t");
            database.bookname = Console.ReadLine();
            Console.Write("Enter book price:\t");
            database.price = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter book category:\t");
            database.category = Console.ReadLine();
 
 
            //Displaying value of language variable
            Console.Write("\n\n===================");
            Console.Write("\n\t\tLanguage\n");
            Console.Write("===================\n\n");
 
            Console.Write("Book Name:\t{0}", language.bookname);
            Console.Write("\nBook Price:\t{0}", language.price);
            Console.Write("\nBook Category:\t{0}", language.category);
 
            Console.Write("\n\n==================\n");
            Console.Write("\t\tDatabase\n");
            Console.Write("====================\n\n");
 
            Console.Write("Book Name:\t{0}", database.bookname);
            Console.Write("\nBook Price:\t{0}", database.price);
            Console.Write("\nBook Category:\t{0}", database.category);
 
            Console.ReadLine();
        }
    }
}

In the preceding example, we create a structure named book that contain three variables as bookname, price, category. These variables can be accessed by creating the object of book structure. Next, we create two variables of book as language and database. Then store the value in language and database and display the value on console.