C# Multidimensional and Jagged Arrays Tutorial For Beginners With Examples

As described earlier, an array is used to store same type of data.

Classification of Arrays

Arrays in C# can be classified as below:
  • Single-Dimensional Arrays
  • Multidimensional Arrays
  • Jagged Arrays
Arrays with single dimension has been discussed in the earlier chapters of this tutorial. In this chapter we will discuss Multidimensional and Jagged arrays.

C# Hashtable Tutorial For Beginners With Examples

A C# Hashtable represents a collection in which objects are stored and retrieved using a key.
Each key in a Hashtable has a hash code using which the objects in a Hashtable are organized.

Create a Hashtable in C#

A Hashtable can be created using the below code:
    Hashtable shoppingCart = new Hashtable();

C# Stack Tutorial For Beginners With Examples

Stack is a type of collection in which the item stored last is retrieved first. This behaviour is also called as LIFO i.e. Last In First Out.
Inserting an item into a Stack is called as Pushing and removing an item is called as Popping.

Important features of C# Stack class

Below are some of the important features of a Stack class.
  • Stack allows Null values.
  • Stak allows duplicate values.
  • It has both generic and non-generic versions.

C# Queue Tutorial For Beginners With Examples

Queue is a type of collection in which the item stored first is retrieved first. This behaviour is also called as FIFO i.e. First In First Out.
Inserting an item into a Queue is called as Enqueuing and removing an item is called as Dequeuing.

Important features of C# Queue class

Below are some of the important features of a Queue class.
  • Null values can be stored in Queue.
  • Duplicate values can be stored in Queue.
  • It has both generic and non-generic versions.

C# Arraylist Tutorial For Beginners With Examples

An Arraylist is a collection which can store any item of type object. The number of objects can dynamically increase or decrease.

Important features of C# Arraylist class

Below are some of the important features of an Arraylist class.
  • Arraylist is a weakly typed collection object.
  • Arraylist may or may not be sorted by default.
  • It can store billions of elements.
  • To access an item in an Arraylist indexes are used.
  • It allows null values.
  • It allows duplicate elements.
  • Performance wise Arraylist is slower compared to generic List.

C# List Tutorial For Beginners With Examples

C# List is one of the most popular collection class. A List object can dynamically increase or decrease in size.
Another collection class Arraylist is also similar to a List class. The primary difference between an Arraylist and a List is that a List is strongly typed class whereas an Arraylist is not.

What is a Strongly Typed Collection Class?

When the type of objects that can be stored in a collection class can be predefined then those type of Collection Classes are called as strongly typed.
These type of classes for which data type can be predefined are called as Generic types. In C#, the generic List class is available.

C# Dictionary Tutorial For Beginners With Examples

A C# Dictionary is one of the most important and widely used collections classes. It consists of keys and corresponding values.
Dictionary<Tkey,Tvalue> is a generic class so the datatype of the keys and the values can be pre defined. Performance wise Dictionary objects are very efficient.

Initialize Dictionary object

Initialization of a Dictionary<Tkey,Tvalue> object can be done as shown below:
    Dictionary<string, string> dictFruits = new Dictionary<string, string>();
    
In the above example the dictionary object has a key of datatype string and value of datatype string.
The Dictionary generic class is part of System.Collections.Generic namespace.

C# Collections Tutorial For Beginners With Examples

Collections helps in storage of data in an orderly way. The data stored in a Collection are called as items or elements. Collections are preferred when the number of items to be stored is not predetermined. Hence, collections are dynamic in nature and their size can increase or decrease during the execution of a program.
There are various type of collections classes and these can be found in the below namespaces:-
  • System.Collections
  • System.Collections.Generic
  • System.Collections.Specialized
  • System.Collections.Concurrent
  • System.Collections.ObjectModel

C# Generics Tutorial For Beginners With Examples

Generics in C#.NET allows a Class, Method, Interface or Delegate to be created without the need of using a specific data type within them.
The assignment of the actual data type is done during the declaration and instantiation of a class, interface and delegate or during the invocation of a method.

Important Features of Generics

Below some of the important features of C# Generics has been provided.
  • Performance wise a generic type is more efficient.
  • It guarantees type safety.
  • It helps in code reusability.
  • It is commonly used in the collection classes.
  • .NET framework uses System.collections.generic namespace for all the generic collection classes.
  • It allows programmers to create their own generic classes, methods, interfaces, delegate and events.
  • Type information about types used in a generic data type is only available in runtime. Reflection can be used to get this information.

C# Events Tutorial For Beginners With Examples

An event is a way to notify same or other classes on the occurrence of an action.
The action can be click of a button in a .NET application, key pressed in a keyboard, a mouse click and so on.

Declaring Events

In C# Events are declared using Delegates. So to declare an Event first a Delegate type has to be declared.
In the below code a PrintHandler Delegate type has been created.
    public delegate void PrintHandler();
        
Once a Delegate type is available an Event can be declared as below:
    public static event PrintHandler PrintEvent;

C# Delegates Tutorial For Beginners With Examples

A Delegate is an object that can hold the address of a method.
A Delegate object can refer only those methods whose signature matches with the Delegate type.

Creating Delegate Types

Delegate types in C# can be created as below:
    public delegate void Add(int number1, int number2);   
        
In the above example Add is the Delegate type and a Delegate object of this type can refer any method that matches the signature of this Delegate type.

Initializing a Delegate

A Delegate object can be initialized by referring a method with a matching signature.
In the below example a method called as AddNumbers with matching signature is created. Then a Delegate object calculate of type Add is initialized with the address of method AddNumbers.
        
    public delegate void Add(int number1, int number2);

    private static void AddNumbers(int firstNumber, int secondNumber)
    {
        Console.WriteLine(firstNumber + secondNumber);
    }

    static void Main(string[] args)
    {
        //Delegate initialized
        Add calculate = AddNumbers;

        Console.ReadLine();
    }      
        
Delegates in C# are like function pointers used in C and C++.

C# Reflection Tutorial For Beginners With Examples

Reflection is a technique using which a program can be modified during runtime. Using reflection a program's behavior can be manipulated dynamically and a program can be made more adaptable.
To work with reflection the required classes are provided in System.Reflection namespace.

Features of C# Reflection

Important features of Reflection are mentioned below.
  • Accessing Metadata - Ability to access metadata associated with an assembly, class and its members.
  • Discovering Types - Allows to discover the types available in an Assembly.
  • Late Binding - Can be used to get or set properties, invoke methods, access fields of an object dynamically instantiated during runtime. This is also know as dynamic invocation.
  • Reflection Emit- Can be used to dynamically create types during runtime.
In this tutorial we will discuss only the first three features as the fourth feature is very rarely used in programming world.

C# Attributes Tutorial For Beginners With Examples

Attributes allow declarative information or metadata to be associated with an assembly, class, method, property and other programming elements in C#.
In C#, the Attribute names are enclosed in square brackets [] and mentioned before the class or method name. Some commonly used Attribute names are System.Serializable and System.Obsolete.

Features of C# Attributes

The important features of C# Attributes are discussed below:
  • Attributes allows metadata to be added to an assembly or programming element. Metadata is additional data or information about a type or assembly.
  • .NET allows one or more attributes to be added to an assembly or programming element like class, method, properties etc.
  • Internally all the Attributes are defined as a class in .NET Framework.
  • Like methods and properties, attributes can also have arguments.
  • The metadata associated with a programming element can be checked by the same program or another program using a process called as Reflection.

C# Exceptions Tutorial For Beginners With Examples

An exception in C# happens when during the execution of a program an error condition occurs.
These exceptions can be generated by the program being executed or by another program being called by the current program. Exceptions can also happen due to the environment in which the application is running or due to any external circumstances.

Exception Handling in C#

When an exception is not handled properly then .NET runtime abruptly halts the execution of a program.
If an exception is handled properly then either the program execution can be continued or can be stopped by doing some meaningful activities like logging the error or performing clean up operations.
Exceptions are handled by using try,catch and finally blocks.
  • try - The code which is suspected to generate an exception should be written inside the try block.
  • catch - The code to handle the exception should be written inside the catch block.
  • finally - The code which must be executed whether an exception is thrown or not should be written inside the finally block.

C# Polymorphism Tutorial For Beginners With Examples

Polymorphism means an object which has different forms.
Polymorphism is exhibited when different objects expose the same type of methods and properties but with different behavior.

Implementing Polymorphism

Below ways can be used to achieve polymorphism in C#:

Polymorphism through Interfaces

Polymorphism can be achieved using interfaces. Different classes using the same interface will expose the same methods and properties. These methods from different classes may behave differently.
Lets create an interface ICalculate having a Calculate method.
    public interface ICalculate
    {
        int Calculate(int x, int y);
    }

C# Structs Tutorial For Beginners With Examples

A Struct is a value type and is maintained by .NET runtime on the Stack memory area. The Struct type is usually used for small groups of related variables.
It is suitable for representing light weight objects such as mathematical objects like Rectangle, Polygons etc. or objects like Color, Employee records etc.
To declare a struct type the struct keyword is used.

Defining C# Structs

Structs are also called as structures and are efficient in terms of performance.
In the below example we have created a new user-defined value type called as Rect. Like int, bool etc. we can now declare a variable of type Rect.
    using System;
    public struct Rect
    {
        public int x, y;

        public Rect(int p1, int p2)
        {
            x = p1;
            y = p2;
        }
    } 

C# Interfaces Tutorial For Beginners With Examples

An interface contains signatures of methodspropertiesevents and indexers.
class or struct implementing the interface should provide implementation of the methods, properties, events and Indexers declared in the interface.

Creating Interfaces

Just like class, an interface is created using the interface keyword. Access modifiers cannot be used inside an interface. All the members of an interface are public by default.
    protected interface ICalculate
    {
        int multiply(int x, int y);
    }
        
An interface is very similar to an abstract class that has only abstract members.

Implementing Interfaces

A class or struct implementing an interface must provide functionalities of all the members declared in an interface.
    class Calculate: ICalculate
    {
        int result;

        public int multiply(int x, int y)
        {
            result = x * y;
            return result;
        }
    }

C# Inheritance Tutorial For Beginners With Examples

The process through which the properties and behavior of an existing class is inherited by another class is called as Inheritance.
The inheriting class can use the methods of the other class like its own method.

Base And Derived Class

Inheritance is one of the fundamentals of Object Oriented Programming (OOP) along with EncapsulationAbstraction and Polymorphism.
As C# is a Object Oriented Programming Language so it supports Inheritance, Encapsulation, Abstraction and Polymorphism.

Base Class

The class whose properties and behaviors are being inherited.

Derived Class

The class which is inheriting the properties and behaviors of another class.
As a standard, derived class should always be a specialization of the base class.
If there is a base class called as Person then there can be one derived class called as Employeeand another called as Customer.
An Employee is a Person and a Customer is also a Person. Hence, a derived class should always have an "is a" relationship with the base class.
Derived classes can use the members of the base class and can also add members of its own.

C# Properties Tutorial For Beginners With Examples

In C#, properties are members of a class or struct that expose private fields. Hence, using properties values can be read from or assigned to private fields.
In addition to class and structs, properties can also be part of an interface. This is done using the auto-implemented properties.

Type of Properties in C#

Properties use accessors to read or write data.
Based on the type of operations, properties can be divided into below categories:
  • Read-only property
  • Write-only property
  • Read/Write property

Read-only Property

Read-only properties use the get accessor to read data from fields.
    public class Employee
    {
        private string _language;

        public string Language
        {
            get
            {
                return _language;
            }
        }
    }

C# Access Modifiers Tutorial For Beginners With Examples

Types and members in C# have certain accessibility level. This accessibility level is enforced by using the Access modifiers (Also called as Access specifiers).
Access modifiers decide whether a Type or a Member should be visible to other code from inside a assembly or from other assemblies.

Access Modifiers in C#

Following Access modifiers are available in C#:
  • public
  • protected
  • internal
  • protected internal
  • private

Public Access Modifier

Types or type members having a public access modifier can be accessed by any program. There are no restrictions on accessing a public type or member.
    public class Data
    {
        public int axisX;
        public int axisY;
    }

    static void Main(string[] args)
    {
        Data data = new Data();

        data.axisX = 100;
        data.axisY = 300;

        Console.WriteLine("Axis X is {0} and Y is {1}", data.axisX, data.axisY);

        Console.ReadLine();
    }
        
Output:
Axis X is 100 and Y is 200

C# Namespaces Tutorial For Beginners With Examples

Namespaces are used to group set of related types and hence helps in organizing the code.
Types with same names can exist within different namespaces to create globally unique types.

Creating a Namespace

A namespace is created by using the keyword namespace followed by the namespace name. Below example shows the usage of namespace in a C# program.
    namespace HelloWorld
    {  
        class Employee
        {           
            void Employee()
            {

            }
        }
    }
        

Contents of a namespace

In C#, a namespace can have the following types within it:

C# Classes Tutorial For Beginners With Examples

A class defines a type. Thus, it allows custom types to be created in a C# program. A class consists of variables, constants, methods, properties and events.

Syntax of a Class

C# classes have a simple syntax. The class keyword is used to declare a class.
<access modifier> class <class name>
{

}             
  • Access modifier: A C# class can have an access modifier which specifies how a class can be accessed. More about access modifiers will be covered in the later part of this tutorial.
  • Class name: Class name is used to identify a class.

Creating a Class

In C#, class keyword is used to declare a class and the class name follows this keyword. In the below example since public is used as an access modifier so anyone can create an object of this class.
    public class Employee
    {
        //Variables

        //Methods

        //Events
    }  

C# Methods Tutorial For Beginners With Examples

A method is a code block that performs a task and gets executed when it is called from the same or another program.

Method Signatures

The syntax of a C# method is shown below:
<access modifier> <return type> <method_name> (parameter1,parameter2...parameterN)
{
    return parameter1;
}              
  • Access modifier: C# methods have an access modifier which specifies how a method can be accessed. More about access modifiers will be covered in the later part of this tutorial.
  • Return type: Methods can specify a return data type. The return type is a data type compatible with the type returned by the method. If a method is not returning anything then return type should be void.
  • Method name: Every method in C# have a name which identifies the method.
  • Parameters: Parameters are the values passed to the method from outside. Methods may or may not have parameters.
  • Return values: A method may or may not return a value. If it is returning some value then return keyword should be used to do so.

C# While Loop Tutorial For Beginners With Examples

C# while loops execute a block of code repeatedly until a specific condition is true.

Type of while Loops in C#

There are two type of while loops in C#:
  • while loop
  • do...while loop

C# while Loop

A C# while loop iterates through a block of code until a specific condition is true.
The syntax of a while loop is shown below:
while(condition)
{
    Code to be executed;
}              
The example below sets a variable iCount to 1 and then checks whether the value of iCount is less than or equal to 10. The iteration stops once the value of the variable iCount becomes greater than 10.
    int iCount = 1;

    while (iCount <= 10)
    {
        Console.WriteLine(iCount);
        iCount++;
    }

C# For Loop Tutorial For Beginners With Examples

C# for loops execute a block of code repeatedly.

Type of for Loops in C#

There are two type of for loops in C#:
  • for loop
  • foreach loop

C# for Loop

A for loop in C# is used when it is known in advance the number of times a code block has to be executed.
The syntax of a for loop is shown below:
for (Initialize; Condition; Increment)
{
    Code to be executed;
}              
  • In the Initialize step a variable is used as a counter and is initialized to a numeric value. The counter variable can be declared in this step or can be declared prior to the start of for loop.
  • The Condition is evaluated in the start of each iteration. If it is true then the iteration continues or else the iteration stops and the code after the for loop executes.
  • After each iteration the counter variable is Incremented.

C# Switch Tutorial For Beginners With Examples

A switch is a simple yet powerful statement that allows C# programs to take decisions based on certain conditions.

C# switch Syntax

A switch statement has a switch section inside which number of case labels are present.
switch (expression)
{
    case constant1:
        Console.WriteLine("Perform Action1.");
        break;
    case constant2:
        Console.WriteLine("Perform Action2.");
        break;
    default:
        Console.WriteLine("Perform default Action.");
        break;
}  

C# If...Else Tutorial For Beginners With Examples

C# has provided conditional statements to allow decision making in a program.
These conditional statements allows a program to execute different sets of code based on certain conditions.

Different varieties of if-else construct is used to route the logic of a program in different paths. The following varieties of if-else are discussed below:
  • if statement
  • if...else statement
  • else...if statement
  • Nested if statements
  • Nested if...else statements
  • switch statement
  • Nested switch statements