C# Tutorial: The Fundamentals you Need to Master C#

Last updated on Nov 26,2019 7.3K Views
Tech Enthusiast working as a Research Analyst at Edureka. Curious about learning... Tech Enthusiast working as a Research Analyst at Edureka. Curious about learning more about Data Science and Big-Data Hadoop.

C# Tutorial: The Fundamentals you Need to Master C#

edureka.co

C# is all-purpose and the robust programming language developed by Microsoft Corporation in the year 2000 as a deadly competitor to Java. It is most popular and a dominating programming language when it comes to both web development as well as desktop application development.

In this C# Tutorial, we will learn the following concepts.

 

C# Basics

 

Introduction to C# Programming Language

Back in the early 90s, Java was the leading programming language for web development, desktop application development and many other fields. Microsoft wanted to come up with a competitor with many advanced features that can leave Java far behind.

It was in the year 2000, Anders Hejlsberg and his Microsoft team in came up with the idea of C# popularly called as C-Sharp. This initiative was approved by the International Standards Organisation (ISO) and the European Computer Manufacturers Association (ECMA). and finally, The C# enters the world of software development

 

Features of C# Programming Language

Object-Oriented Programming approach is what makes C# sharp to be the most programmer-friendly and easy to develop and maintain programming language.

The meaning of Type-Safe is that the compiler will be given access only to the memory location that has the permission to execute. This feature improves the code safety to an exponential level.

The feature of Interoperability makes C# capable enough to do everything that is native to C++ in a more efficient way that can outperform C++ itself.

C# provides access to multiple numbers of in-built libraries that provide preprogrammed functionalities to decrease the time spent in the development process.

 

C# was designed to be superior amongst the other programming languages. Hence, it is always open to updates and it keeps itself highly scalable with its features.

The developers at Microsoft used the component-based approach to develope C#. This is the most predominant development methodology to keep C# highly scalable and updated.

The Structured Programming approach is preferred during the software development life-cycle as it becomes easy to develop compile and deploy the software compared to the procedure-oriented programming approach.

C# Programming happens to be faster in compilation and execution compared to C++ and other programming languages.

 

Installation 

It is proven that Microsoft Visual Studio is the best in class Editor for C# Programming. We will install and Set up Microsoft Visual Studio for executing our C# Programs by following the steps mentioned below:

Step 1: Download Microsoft Visual Studio

Google for the latest version of Visual Studio and download the installer file into your local system and then run the installer file as an administrator.

 

 

Step 2: Select the .NET Desktop Development Package 

Once you run the Installer, the Visual Studio Editor will be successfully downloaded into your local system, Later a dialogue box will be displayed on your desktop screen asking foe a particular package you need in your system. Here, you need to select the .NET Desktop Development package.

 

 

Step 3: Set C# Environment

Once your packages for .NET Development are downloaded, then another dialogue box will be displayed on your screen asking for the development environment you are looking for. Here, you need to select the environment for C#.

 

Step 4: Create your First Project

Once the environment is set, you are all good to go. Start your Visual Studio and select create new project option in the displayed dialogue box.

You will be redirected to the next dialogue box and there you need to select Class library as .NET Standard as shown below.

In the next dialogue box, you will be asked to Configure your project. Configure it and you are now in the Editor. Write your first program and run it. The output will be successfully displayed on the Command Prompt.

using System;
class Edureka
{
     static void Main(string[] args)
    {
         Console.WriteLine("Welcome to Edureka!, Happy Learning..!");
    }
}

 

 

//Output:

Let us execute our first C# Program.

 

C# Program Structure

Now that we have executed our first C# Program, let us understand its structure in detail. A simple C# program has the following parts.

using System;  
namespace ConsoleApplication1  
{  
    public class Edureka  
    {  
        public static void Main(string[] args)  
        {  
            Console.WriteLine("Welcome to Edureka!, Happy Learning..!");  
        }  
    }  
}

//Output:

Welcome to Edureka!, Happy Learning..!

 

Now, let us learn the Datatypes available in C#.

 

Datatypes

The datatypes in C# are divided into three categories are described below.

 

Value Datatypes

The Value Datatypes are located in the System.ValueType Library and are always ready to be directly accessed and variables can be directly assigned to a particular value. The Value Datatypes are further classified into two types as shown below:

Predefined Datatypes: These are the ones which we normally use in our day to day programming. These Datatypes are predefined by the language developers and are kept ready to use for the programmers.

Example:

int, float, char, short double, etc

User-Defined Datatypes: There are situations where we might need to store different values from Datatypes into one single variable. In these cases, the Predefined Datatypes aren’t just enough. User-Defined Datatypes are like customizable datatypes for the user.

Example: Structure, Enum

DatatypeRange of the Memory AllocatedMemory Size
signed char-128 to 127  1 Byte
unsigned char 0 to 127 1 Byte
char-128 to 127  1 Byte
signed short-32,768 to 32,767  2 Bytes
unsigned short 0 to 65,535 2 Bytes
short-32,768 to 32,767  2 Bytes
signed int-2,147,483,648 to -2,147,483,647  4 Bytes
unsigned int 0 to 4,294,967,295  4 Bytes
int-2,147,483,648 to -2,147,483,647  4 Bytes
signed long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807  8 Bytes
 unsigned long 0 to 18,446,744,073,709,551,615  8 Bytes
 long-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807  8 Bytes
 float1.5 * 10-45 – 3.4 * 1038, (7-digit precision)  4 Bytes
 double5.0 * 10-324 – 1.7 * 10308, (15-digit precision)  8 Bytes
 decimal-7.9 * 10-28 – 7.9 * 1028, (28-digit precision)  16 Bytes


Pointer Datatype

Pointer Type is a simple datatype. Its functionality is completely similar to the Pointers in C. They are designed to store the address of another pointer.

float* ptr;

 

Reference Datatypes

The name is self-explanatory. The Reference Datatypes actually do not store the variables, instead, they store the reference value to that particular variable. In other words, they store the address of the actual variable.

The Reference Variables are classified into three different types as mentioned below:

The Object Datatype is available in the System.Object Class. The object types can be assigned to the values of the other types, reference types, predefined, user-defined types. But, before assignment values, it requires type conversion.

object abc;
abc = 50;  //this is called boxing

Dynamic Type variables are designed to store almost all types of values. It is called as Dynamic Type because the type-checking of values takes place in run-time

dynamic x=10;

The String Type is available in System.String class. The String Type is designed to store string literals. The String Literals are stored in two forms in two forms

String S = "Edureka";
@"Edureka";

Now let us understand the variables.

 

Variables

Variables are the names allotted for the memory location that store certain data given by the user and that data is easily accessible by using the variable name. There are five types of variables available in C#

TypeExample
NullNull data
BooleanTrue and False
IntegerInt, Char, Byte, Short, Long
FloatFloat and Double
DecimalDecimal

Example:

int a, b;  
double x;      
float p;      
char abc;

Rules to be followed to declare variables in C#

 

Operators

An Operator can be defined as a special symbol that explains the computer to perform a particular Mathematical are a Logical Operation upon a set of variables. C# includes a variety of Operators which are mentioned as below.

Arithmetic Operators

OperatorExampleDescription
+A + BAdds two Operands
A – BSubstracts two Operands
*A * BMultiples two Operands
/A / BDivides two Operands
%A % BThe remainder of Two Operands
++A++Increment Operation
A–Decrement Operation

 

Relational Operators

OperatorExampleDescription
==A == BTrue, if both operands are equal, Else False
!=A != BTrue, if both operands are not equal, Else False
>A > BTrue, if A is Greater, Else False
<A < BTrue, if B is Greater, Else False
>=A >= BTrue, if A is Greater or equal, Else False
<=A <= BTrue, id B is Greater equal, Else False

 

Logical Operators

OperatorExampleDescription
&&A && BTrue, if both operands are true, Else False
||A || BTrue, if one of the operands is true, Else False
!A ! BReverses the logical state of the operand

 

Bitwise Operators

ABA & BA | BA ^ B
11110
10011
01011
00000

 

OperatorExampleDescription
~(~A)Binary One’s Complement Operator is unary and has the effect of ‘flipping’ bits.
<<A<<2Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
>>A>>2Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.

 

Assignment Operators

OperatorExampleDescription
=A = B+CA=B+C, B+C is assigned to A
+=A += BA=A+B, A+B is assigned to A
-=A -= BA=A-B, A-B is assigned to A
*=A -= BA=A*B, A*B is assigned to A
/=A /= BA=A/B, A/B is assigned to A
%=A %= BA=A%B, A%B is assigned to A
<<=A <<= 2Left Shift and Assignment Operator
>>=A >>= 2Right Shift and Assignment Operator
&=A &= 2Bitwise and Assignment Operator
^=A ^= 2Bitwise Exclusive and Assignment Operator
|=A != 2Bitwise Inclusive and Assignment Operator

 

Loops

loop statement is used for executing a block of statements repeatedly until a particular condition is satisfied. The C# Language consists of the following Loop Statements.

For Loop

The for loop is used to execute a particular code segment for multiple times until the given condition is satisfied. 

Syntax

for(initialization; condition; increment/decrement)
{  
	//code segment
}

FlowChart:

Example:

using System;
public class ForExample
{
    public static void Main(string[] args)
    {
        for (int i = 1; i<= 5; i++)
        {
            Console.WriteLine(i);
        }
    }
}

//Output:

1
2
3
4
5

 

While Loop

The While loop is used to execute a code segment for multiple numbers of times until a specific condition is satisfied.

Syntax

while(condition)
{  
	//code to be executed  
} 

FlowChart:

Example:

using System;

namespace Loops
{
    class Program
    {
           static void Main(string[] args)
           {
                  int x = 5;
                  while (x<= 10)
                  {
                        Console.WriteLine("The value of a: {0}", x);
                        x++;
                  }
                  Console.ReadLine();
           }
     }
}

//Output:

The value of a: 5
The value of a: 6
The value of a: 7
The value of a: 8
The value of a: 9
The value of a: 10

 

Do While Loop

Do while loop is completely similar to While Loop but the only difference is that the condition is placed at the end of the loop. Hence, the loop is executed at least for once.

Syntax

do
{  
	//code to be executed  
}while(condition); 

FlowChart:

Example:

using System;
namespace Edureka
{
    class DoWhileLoop
    {
        public static void Main(string[] args)
        {
            int i = 1, n = 5, product;
            do
            {
                product = n * i;
                Console.WriteLine("{0} * {1} = {2}", n, i, product);
                i++;
            } while (i<= 10);
        }
    }
}

//Output:

5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

 

Conditional

Conditional statements are used to execute statement or group of statements based on some condition. If the condition is true then C# statements are executed otherwise the next statement will be executed.

Different types of Conditional Statements in C++ Language are as follows:

  1. If statement
  2. If-Else statement
  3. Nested If-else statement
  4. If-Else If ladder
  5. Switch statement

If statement

The single if statement in C# language is used to execute the code if a condition is true. It is also called one-way selection statement.

Syntax

if (boolean-expression)
{
	// statements executed if boolean-expression is true
}

FlowChart:

Example:

using System;
namespace Conditional
{
    class IfStatement
    {
        public static void Main(string[] args)
        {
            int number = 2;
            if (number<5)
            {
                Console.WriteLine("{0} is less than 5", number);
            }
            Console.WriteLine("This statement is always executed.");
        }
    }
}

//Output:

2 is less than 5
This statement is always executed.

 

If-Else statement

The if-else statement in C language is used to execute the code if the condition is true or false. It is also called two-way selection statement.

Syntax

if (boolean-expression)
{
	// statements executed if boolean-expression is true
}
else
{
	// statements executed if boolean-expression is false
}

FlowChart:

Example:

using System;
namespace Conditional
{
    class IfElseStatement
    {
        public static void Main(string[] args)
        {
            int number = 12;
            if (number<5)
            {
                Console.WriteLine("{0} is less than 5", number);
            }
            else
            {
                Console.WriteLine("{0} is greater than or equal to 5", number);
            }
            Console.WriteLine("This statement is always executed.");
        }
    }
}

//Output:

12 is greater than or equal to 5
This statement is always executed.

 

Nested If-else statement

The nested if-else statement is used when a program requires more than one test expression. It is also called a multi-way selection statement. When a series of the decision are involved in a statement, we use if-else statement in nested form.

Syntax

if (boolean-expression)
{
	if (nested-expression-1)
	{
		// code to be executed
	}
	else
	{
	// code to be executed
	}
}
else
{
	if (nested-expression-2)
	{
		// code to be executed
	}
	else
	{
		// code to be executed
	}
}

FlowChart:

Example:

using System;

namespace Conditional
{
      class Nested
      {
             public static void Main(string[] args)
             {
                   int first = 7, second = -23, third = 13;
                   if (first &gt; second)
                   {
                        if (first<third)
                        {
                              Console.WriteLine("{0} is the largest", first);
                        }
                        else
                        {
                               Console.WriteLine("{0} is the largest", third);
                        }
                   }
                   else
                   {
                        if (second<third)
                        {
                              Console.WriteLine("{0} is the largest", second);
                        }
                        else
                       {
                               Console.WriteLine("{0} is the largest", third);
                       }
                   }
             }
      }
}

//Output:

13 is the largest

 

Else-if Ladder

The if-else-if statement is used to execute one code from multiple conditions. It is also called multipath decision statement. It is a chain of if..else statements in which each if statement is associated with else if statement and last would be an else statement.

Syntax

if(condition1)
{  
    // code to be executed if condition1 is true  
}
else if(condition2)
{  
    // code to be executed if condition2 is true  
}  
else if(condition3)
{  
    // code to be executed if condition3 is true  
}  
... 
else
{
    // code to be executed if all the conditions are false  
}

FlowChart:

Example:

using System;

class Edureka
{
     public static void Main(String[] args)
     {
          int i = 20;
          if (i == 10)
              Console.WriteLine("i is 10");
          else if (i == 15)
              Console.WriteLine("i is 15");
          else if (i == 20)
              Console.WriteLine("i is 20");
          else
              Console.WriteLine("i is not present");
     }
}

//Output:

i is 20

 

Switch statement

Switch statement acts as a substitute for a long if-else-if ladder that is used to test a list of cases. A switch statement contains one or more case labels which are tested against the switch expression. When the expression match to a case then the associated statements with that case would be executed.

Syntax

switch (variable/expression)
{
    case value1:
        // Statements executed if expression(or variable) = value1
        break;
    case value2:
        // Statements executed if expression(or variable) = value1
        break;
    ... ... ... 
    ... ... ... 
    default:
        // Statements executed if no case matches
}

FlowChart:

Example:

using System;

namespace Conditional
{
     class SwitchCase
     {
          public static void Main(string[] args)
          {
               char ch;
               Console.WriteLine("Enter an alphabet");
               ch = Convert.ToChar(Console.ReadLine());
               switch (Char.ToLower(ch))
               {
                     case 'a':
                     Console.WriteLine("Vowel");
                     break;
                     case 'e':
                     Console.WriteLine("Vowel");
                     break;
                     case 'i':
                     Console.WriteLine("Vowel");
                     break;
                     case 'o':
                     Console.WriteLine("Vowel");
                     break;
                     case 'u':
                     Console.WriteLine("Vowel");
                     break;
                     default:
                     Console.WriteLine("Not a vowel");
                     break;
               }
          }
     }
}

//Output:

Enter an alphabet
e
Vowel

 

Strings

String Datatype is a member of System.String Class. It is capable to store character type of data. We can perform various operations on Stings such as concatenation, comparison, getting substring, search, trim, replacement and many more.

The analogy of String and string

In C# String and string are equivalent. The word string is a keyword and acts as the System.String class. We can use either of the versions to declare strings.

Syntax:

string s1 = "Edureka";//creating string using string keyword  
String s2 = "Happy Learning";//creating string using String class  

Example:

using System;
public class StringExample
{
    public static void Main(string[] args)
    {
        string s1 = "Edureka";
        char[] ch = { 'C', 's', 'h', 'a', 'r', 'p',' ','T','u','t','o','r','i','a','l' };
        string s2 = new string(ch);
        Console.WriteLine(s1);
        Console.WriteLine(s2);
    }
}

//Output:

Edureka
Csharp Tutorial

 

String Methods in C# 

MethodDescription
Clone()Used to return a reference to this instance of String.
Compare(String, String)Used to compare two specified String objects.
Concat(String, String)Concatenate two specified instances of String.
Contains(String)Return a value indicating a specified sub-string
Copy(String)Used to create a new instance of String with the same value
CopyTo(Int, Char[], Int, Int)Copies characters from a specified position
Equals(String, String)Determines that two String objects have the same value.
Format(String, Object)Replace one or more format items in a specified string
IndexOf(String)Reports the zero-based index of the first occurrence
Insert(Int32, String)Returns a new string in which a string is inserted at an index.
IsInterned(String) Indicates that this string is in Unicode normalization form C.
IsNullOrEmpty(String)Indicates that the specified string is null or an empty string.
IsNullOrWhiteSpace(String)Used to indicate whether a specified string is null, empty,
Join(String, String[])Used to concatenate all the elements of a string array
LastIndexOf(Char)  Reports the zero-based index position of the last character
LastIndexOfAny(Char[])Reports the zero-based index position of the last character
Remove(Int32)Returns a new string in which all the characters
Replace(String, String)Returns a new string in which all occurrences of a string
Split(Char[])It is used to split a string into substrings
StartsWith(String)It is used to check whether the beginning of this string
Substring(Int32)It is used to retrieve a substring from this instance.
ToCharArray() Copies the characters in this instance to a Unicode array.
ToString()It is used to return the instance of String.
Trim()Trims the string


Arrays

Similar to other programming languages, C# does have arrays. Arrays are the simple data structures that are designed to store the same datatype of elements in a contiguous memory location.

C# supports the following Array types.

Single Dimensional Array

Single Dimensional Array stores elements in the form of one single row.

Syntax

int[] arr = new int[5];//creating array  

Example:

using System;
public class ArrayExample
{
    public static void Main(string[] args)
    {
        int[] arr = new int[5];        arr[0] = 10;
        arr[1] = 20;
        arr[2] = 30;
        arr[3] = 40;
        arr[4] = 50;
        for (int i = 0; i < arr.Length; i++)
        {
            Console.WriteLine(arr[i]);
        }
    }
}

//Output:

10
20
30
40
50

 

Multidimensional Array

Multidimensional Array stores elements in the form of multiple dimensions like a matrix and a cube etc.

Syntax

int val = a[2,3];

Example:

using System;

namespace ArrayApplication
{
     class MyArray
     {
           static void Main(string[] args)
           {
                  int[,] a = new int[5, 2] { { 0, 0 }, { 1, 2 }, { 2, 4 }, { 3, 6 }, { 4, 8 } };
                  int i, j;
                  for (i = 0; i < 5; i++)
                  {
                          for (j = 0; j < 2; j++)
                          {
                                 Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i, j]);
                          }
                  }
                  Console.ReadKey();
           }
     }
}

//Output:

a[0,0] = 0
a[0,1] = 0
a[1,0] = 1
a[1,1] = 2
a[2,0] = 2
a[2,1] = 4
a[3,0] = 3
a[3,1] = 6
a[4,0] = 4
a[4,1] = 8

 

Jagged Array

Jagged Array is simply an array of arrays.

Example:

using System;

namespace ArrayApplication
{
     class MyArray
     {
           static void Main(string[] args)
           {
                  int[][] a = new int[][]{new int[]{0,0},new int[]{1,2},
                  new int[]{2,4},new int[]{ 3, 6 }, new int[]{ 4, 8 } };
                  int i, j;
                  for (i = 0; i < 5; i++)
                  {
                         for (j = 0; j < 2; j++)
                         {
                                Console.WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]);
                         }
                  }
                  Console.ReadKey();
           }
      }
}

//Output:

a[0][0] = 0
a[0][1] = 0
a[1][0] = 1
a[1][1] = 2
a[2][0] = 2
a[2][1] = 4
a[3][0] = 3
a[3][1] = 6
a[4][0] = 4
a[4][1] = 8

 

Collections

Collection can be simply considered as a group of objects collected together so as to apply some functions upon the collected data. The operations that once ca possibly perform on a collection are,

Types of Collections

There are three different possibilities to work with collections. The three namespaces are mentioned below:

The System.Collections.Generic Class has the following varieties of classes:

The System.Collections classes are considered as legacy classes. they include the following classes.

The System.Collections.Concurrent classes namespace provides classes for thread-safe operations. Now multiple threads will not create a problem for accessing the collection items. the classes available in this are,

 

List

The list is considered as a data structure available in System.Collection.Generics namespace. It can store and fetch elements. The list is capable to store duplicate elements.

Example:

using System;
using System.Collections.Generic;

public class Edureka
{
      public static void Main(string[] args)
      {
           var names = new List<string>();
           names.Add("Sandhya");
           names.Add("Arun");
           names.Add("Prashanth");
           names.Add("Kiran");
           foreach (var name in names)
           {
                Console.WriteLine(name);
           }
      }
}

//Output:

Sandhya
Arun
Prashanth
Kiran

 

Hash Set

C# HashSet category is often accustomed store, take away or read components. It doesn’t store duplicate componentsit’s urged to use HashSet category if you’ve got to store solely distinctive componentsit’s found in System.Collections.Generic namespace.

Example:

using System;
using System.Collections.Generic;

public class Edureka
{
     public static void Main(string[] args)
     {
          var names = new HashSet<string>();
          names.Add("Sunil");
          names.Add("Amar");
          names.Add("Pujari");
          names.Add("Imran");
          names.Add("karan");
          foreach (var name in names)
          {
              Console.WriteLine(name);
          }
     }
}

//Output:

Sunil
Amar
Pujari
Imran
karan

 

Sorted Set

C# SortedSet class are often accustomed store, remove or read elements. It maintains ascending order and doesn’t store duplicate elementsit’s prompt to use SortedSet category if you’ve got to store distinctive components and maintain ascending order. it’s found in System.Collections.Generic namespace.

Example:

using System;
using System.Collections.Generic;

public class Edureka
{
     public static void Main(string[] args)
     {
          var names = new SortedSet<string>();
          names.Add("Sanjay");
          names.Add("Anuradha");
          names.Add("Praveen");
          names.Add("Ravi");
          names.Add("Kajol");
          foreach (var name in names)
          {
               Console.WriteLine(name);
          }
      }
}

//Output:

Anuradha
Kajol
Praveen
Ravi
Sanjay

 

Stack

The stack is a simple collection that follows FILO or first in last out procedure while processing the elements stored in it.

Example:

using System;
using System.Collections.Generic;

public class Edureka
{
      public static void Main(string[] args)
      {
            Stack<string> names = new Stack<string>();
            names.Push("Chandan");
            names.Push("Pooja");
            names.Push("James");
            names.Push("Rajesh");
            names.Push("kumar");
            foreach (string name in names)
            {
                   Console.WriteLine(name);
            }
            Console.WriteLine("Peek element: " + names.Peek());
            Console.WriteLine("Pop: " + names.Pop());
            Console.WriteLine("After Pop, Peek element: " + names.Peek());
      }
}

//Output:

kumar
Rajesh
James
Pooja
Chandan
Peek element: kumar
Pop: kumar
After Pop, Peek element: Rajesh

 

Queue

The queue is completely similar to Stack but the only difference is that the Queue follows FIFO or first in and first out principle while processing the elements stored in it.

Example:

using System;
using System.Collections.Generic;

public class Edureka
{
      public static void Main(string[] args)
      {
            Queue<string> names = new Queue<string>();
            names.Enqueue("Srujan");
            names.Enqueue("Prajat");
            names.Enqueue("John");
            names.Enqueue("Raju");
            names.Enqueue("Hari");
            foreach (string name in names)
            {
                  Console.WriteLine(name);
            }
            Console.WriteLine("Peek element: " + names.Peek());
            Console.WriteLine("Dequeue: " + names.Dequeue());
            Console.WriteLine("After Dequeue, Peek element: " + names.Peek());
      }
}

//Output:

Srujan
Prajat
John
Raju
Hari
Peek element: Srujan
Dequeue: Srujan
After Dequeue, Peek element: Prajat

 

Linked List

The linked list is a dynamic memory collection. The elements in the Linked list are stored by accessing the memory from the heap and storing the elements in a continuous order by linking their addresses.

Example:

using System;
using System.Collections.Generic;

public class Edureka
{
      public static void Main(string[] args)
      {
            var names = new LinkedList<string>();
            names.AddLast("Rajat");
            names.AddLast("Arun");
            names.AddLast("Prakash");
            names.AddLast("jay");
            names.AddFirst("sai");
            foreach (var name in names)
            {
                   Console.WriteLine(name);
            }
      }
}

//Output:

sai
Rajat
Arun
Prakash
jay

 

Dictionary

Dictionary category uses the idea of the hashtable. It stores values on the premise of the key. It contains distinctive keys solely. By the assistance of key, we will simply search or take away elementsit’s found in System.Collections.Generic namespace.

Example:

using System;
using System.Collections.Generic;

public class Edureka
{
      public static void Main(string[] args)
      {
            Dictionary<string, string> names = new Dictionary<string, string>();
            names.Add("1", "Shiva");
            names.Add("2", "Prasad");
            names.Add("3", "Preetam");
            names.Add("4", "Roy");
            names.Add("5", "Akash");
            foreach (KeyValuePair<string, string> kv in names)
            {
                  Console.WriteLine(kv.Key + " " + kv.Value);
             }
      }
}

//Output:

1 Shiva
2 Prasad
3 Preetam
4 Roy
Akash

 

Sorted Dictionary

The SortedDictionary category uses the conception of the hashtable. It stores values on the idea of the key. It contains distinctive keys and maintains ascending order on the idea of the key. By the assistance of key, we will simply search or take away elementsit’s found in System.Collections.Generic namespace.

Example:

using System;
using System.Collections.Generic;

public class Edureka
{
     public static void Main(string[] args) 
     {
           SortedDictionary<string, string> names = new SortedDictionary<string, string>(); 
           names.Add("1", "Arun"); 
           names.Add("4", "Vishal");
           names.Add("5", "Ramesh");
           names.Add("3", "Vidya"); 
           names.Add("2", "Pallavi");
           foreach (KeyValuePair<string, string> kv in names)
           {
                 Console.WriteLine(kv.Key + " " + kv.Value);
           }
     }
}

//Output:

1 Shiva
2 Prasad
3 Preetam
4 Roy
5 Akash

 

Sorted List

The SortedList is an array of key/value pairs. It stores values on the premise of the key. The SortedList category contains distinctive keys and maintains ascending order on the premise of the key. By the assistance of key, we are able to simply search or remove elementsit’s found in System.Collections.Generic namespace.

Example:

using System;
using System.Collections.Generic;

public class Edureka
{
       public static void Main(string[] args)
       {
              SortedDictionary<string, string> names = new SortedDictionary<string, string>();
              names.Add("1", "Arun");
              names.Add("4", "Vishal");
              names.Add("5", "Ramesh");
              names.Add("3", "Vidya");
              names.Add("2", "Pallavi");
              foreach (KeyValuePair<string, string> kv in names)
              {
                    Console.WriteLine(kv.Key + " " + kv.Value);
              }
       }
}

//Output:

1 Arun
2 Pallavi
3 Vidya
4 Vishal
5 Ramesh

 

Structure

The structure is a user-defined datatype designed to store multiple elements of the different datatype. The structure is declared using the keyword struct.

Example:

using System;

struct Books
{
     public string title;
     public string author;
     public string subject;
     public int book_id;
};

public class Edureka
{
     public static void Main(string[] args)
     {
          Books Book1;
          Books Book2;
          Book1.title = "C# Programming";
          Book1.author = "Ramchandra Kumar";
          Book1.subject = "C++ Programming Tutorial";
          Book1.book_id = 95908978;
          Book2.title = "Telecom Billing";
          Book2.author = "Karan";
          Book2.subject = "Telecom Billing Tutorial";
          Book2.book_id = 18674900;
          Console.WriteLine("Book 1 title: {0}", Book1.title);
          Console.WriteLine("Book 1 Author: {0}", Book1.author);
          Console.WriteLine("Book 1 subject: {0}", Book1.subject);
          Console.WriteLine("Book 1 book_id:{0}", Book1.book_id);
          Console.WriteLine("Book 2 title: {0}", Book2.title);
          Console.WriteLine("Book 2 Author: {0}", Book2.author);
          Console.WriteLine("Book 2 subject: {0}", Book2.subject);
          Console.WriteLine("Book 2 book_id: {0}", Book2.book_id);
          Console.ReadKey();
     }
}

//Output:

Book 1 title: C# Programming
Book 1 Author: Ramchandra Kumar
Book 1 subject: C++ Programming Tutorial
Book 1 book_id :95908978
Book 2 title: Telecom Billing
Book 2 Author: Karan
Book 2 subject: Telecom Billing Tutorial
Book 2 book_id: 18674900

 

Functions

The function is defined as a block of code of the main code. The function is used to execute statements specified in the code block. A function consists of the following components.

Syntax

<access-specifier><return-type>FunctionName(<parameters>)  
{  
// function body  
// return statement  
} 

Example:

using System;
namespace FunctionExample
{
    class Edureka
    {
        public string Show(string message)
        {
            Console.WriteLine("Inside Show Function");
            return message;
        }
        static void Main(string[] args)
        {
            Edureka program = new Edureka();
            string message = program.Show("To Edureka");
            Console.WriteLine("Welcome " + message);
        }
    }
}

//Output:

Inside Show Function
Welcome To Edureka

Functions can be executed in 3 different ways:

Call by Value

In C#, value-type parameters are that pass a replica of original value to the function instead of reference. It doesn’t modify the first value. An amendment created in passed value doesn’t alter the particular valuewithin the following example, we’ve got pass value throughout the call.

Example:

using System;
namespace CallByValue
{
    class Edureka
    {
        public void Show(int val)
        {
            val *= val; 
            Console.WriteLine("The value inside the show function " + val);
        }
        static void Main(string[] args)
        {
            int val = 50;
            Edureka program = new Edureka(); 
            Console.WriteLine("Value before calling the function " + val);
            program.Show(val);        
            Console.WriteLine("Value after calling the function " + val);
        }
    }
}

//Output:

Value before calling the function 50
The value inside the show function 2500
Value after calling the function 50

 

Call by Reference

In Call by Reference method,  a ref keyword to pass the argument as reference-type. It passes the reference of arguments to the function rather than a copy of the original value. The changes in passed values are permanent and modify the original variable value.

Example:

using System;
namespace CallByReference
{
    class Edureka
    {
        public void Show(ref int val)
        {
            val *= val; 
            Console.WriteLine("The value inside the show function " + val);
        }
        static void Main(string[] args)
        {
            int val = 50;
            Edureka program = new Edureka(); 
            Console.WriteLine("Value before calling the function " + val);
            program.Show(ref val);            
            Console.WriteLine("Value after calling the function " + val);
        }
    }
}

//Output:

Value before calling the function 50
The value inside the show function 2500
Value after calling the function 2500

 

Out Parameter

The Out Parameter provides out keyword to pass arguments as out-type. It is like reference-type, except that it does not require the variable to initialize before passing. We must use out keyword to pass the argument as out-type. It is useful when we want a function to return multiple values.

Example:

using System;
namespace OutParameter
{
    class Edureka
    {
        public void Show(out int val)
        {
            int square = 5;
            val = square;
            val *= val; 
        }
        static void Main(string[] args)
        {
            int val = 50;
            Edureka program = new Edureka(); 
            Console.WriteLine("Value before passing out variable " + val);
            program.Show(out val); 
            Console.WriteLine("Value after recieving the out variable " + val);
        }
    }
}

//Output:

Value before passing out variable 50

Valueafter recieving the out variable 25

 

Now let us move to Object-oriented programming

 

Object-Oriented Programming 

 

Object-oriented programming System is a programming paradigm based on the concept of objects that contain data members and methods related to them. The primary purpose of object-oriented programming is to increase the flexibility and maintainability of programs

Features of object-oriented programming:

The Object-Oriented Paradigms in C# are as follows

 

Enumeration in C#

Enum or also called as an enumeration in C# is used to store constant values without having to alter them during the entire execution of a C# Program. It is used to store a set of named constants such as season, days, month, size etc

Example:

using System;
public class EnumExample
{
      public enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
      public static void Main()
      {
           int x = (int)week.Monday;
           int y = (int)week.Friday;
           Console.WriteLine("Monday = {0}", x);
           Console.WriteLine("Friday = {0}", y);
     }
}

//Output:

Monday = 0
Friday = 4

 

Object-Oriented Programming Approach

The Object-Oriented style of programming can be achieved by following the methods prescribed below.

Encapsulation

Encapsulation is a method to combine the methods along with their data members.

Example:

using System;

namespace Edureka
{
     class Rectangle
     {
            public double length;
            public double width;   
            public double GetArea()
            {
                  return length * width;
            }
            public void Display()
            {
                  Console.WriteLine("Length: {0}", length);
                  Console.WriteLine("Width: {0}", width);
                  Console.WriteLine("Area: {0}", GetArea());
            }
     }
     class ExecuteRectangle
     {
             static void Main(string[] args)
             {
                  Rectangle r = new Rectangle();
                  r.length = 50;
                  r.width = 35;
                  r.Display();
                  Console.ReadLine();
             }
     }
}

//Output:

Length: 50
Width: 35
Area: 1750

 

Abstraction

Abstraction is a method to hide the complex coding part from the user by providing him with only the required information he needs.

Example:

using System;
public abstract class Shape
{
    public abstract void draw();
}
public class Rectangle : Shape
{
    public override void draw()
    {
        Console.WriteLine("drawing rectangle...");
    }
}
public class Circle : Shape
{
    public override void draw()
    {
        Console.WriteLine("drawing circle...");
    }
}
public class TestAbstract
{
    public static void Main()
    {
        Shape s;
        s = new Rectangle();
        s.draw();
        s = new Circle();
        s.draw();
    }
}

//Output:

drawing rectangle...
drawing circle...

 

Interface

The interface is completely similar to Abstraction. The Functionality of an Interface is to hide the unimportant data from the user and provide him with the only important data he needs.

Example:

using System;
public interface Drawable
{
    void draw();
}
public class Rectangle : Drawable
{
    public void draw()
    {
        Console.WriteLine("drawing rectangle...");
    }
}
public class Circle : Drawable
{
    public void draw()
    {
        Console.WriteLine("drawing circle...");
    }
}
public class TestInterface
{
    public static void Main()
    {
        Drawable d;
        d = new Rectangle();
        d.draw();
        d = new Circle();
        d.draw();
    }
}

//Output:

drawing rectangle...
drawing circle...

 

Polymorphism

 

Polymorphism is the combination of “poly” + “morphs” which means many forms. It is a greek word. It means the code segment can take up multiple forms. We have two types of Polymorphism.

Example:

using System;
public class Animal
{
      public string color = "white";
}
public class Dog : Animal
{
      public string color = "black";
}
public class TestSealed
{
      public static void Main()
      { 
            Animal d = new Dog();
            Console.WriteLine(d.color);
      }
}

//Output:

white

 

Inheritance

Inheritance is a process in which one object acquires all the properties and behaviours of its parent object automatically. You can reuse, extend or modify the attributes and behaviours which is defined in other class. the class which inherits the members of another class is called derived class and the class whose members are inherited is called the base class. The derived class is the specialized class for the base class.

Example for Single Level Inheritance

using System;
namespace RectangleApplication
{
     class Rectangle
     {
          protected double length;
          protected double width;
          public Rectangle(double l, double w)
          {
               length = l;
               width = w;
          }
          public double GetArea()
          {
               return length * width;
          }
          public void Display()
          {
               Console.WriteLine("Length: {0}", length);
               Console.WriteLine("Width: {0}", width);
               Console.WriteLine("Area: {0}", GetArea());
          }
     }
     class Tabletop : Rectangle
     {
          private double cost;
          public Tabletop(double l, double w) : base(l, w) { }
          public double GetCost()
          {
                double cost;
                cost = GetArea() * 70;
                return cost;
          }
          public void Display()
          {
                base.Display();
                Console.WriteLine("Cost: {0}", GetCost());
          }
     }
     class ExecuteRectangle
     {
           static void Main(string[] args)
           {
                 Tabletop t = new Tabletop(4.5, 7.5);
                 t.Display();
                 Console.ReadLine();
           }
     }
}

//Output:

Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5

 

Example of Multi-Level Inheritance

using System;

namespace InheritanceApplication
{
      class Shape
      {
           public void setWidth(int w)
           {
                width = w;
           }
           public void setHeight(int h)
           {
                 height = h;
           }
           protected int width;
           protected int height;
      }
      public interface PaintCost
      {
           int getCost(int area);
      }
      class Rectangle : Shape, PaintCost
      {
           public int getArea()
           {
                 return (width * height);
           }
           public int getCost(int area)
           {
                 return area * 70;
           }
      }
      class RectangleTester
      {
            static void Main(string[] args)
            {
                 Rectangle Rect = new Rectangle();
                 int area;
                 Rect.setWidth(5);
                 Rect.setHeight(7);
                 area = Rect.getArea();
                 Console.WriteLine("Total area: {0}", Rect.getArea());
                 Console.WriteLine("Total paint cost: ${0}", Rect.getCost(area));
                 Console.ReadKey();
            }
      }
}

//Output:

Total area: 35
Total paint cost: $2450

 

Overloading 

Overloading is a situation where we have two or members declared using the same name. Overloading is also possible when we declare two or more methods with the same name as well. Let us check examples of both.

Member Overloading

Example:

using System;
public class Edureka
{
    public static int add(int a, int b)
    {
        return a + b;
    }
    public static int add(int a, int b, int c)
    {
        return a + b + c;
    }
}
public class TestMemberOverloading
{
    public static void Main()
    {
        Console.WriteLine(Edureka.add(12, 23));
        Console.WriteLine(Edureka.add(12, 23, 25));
    }
}

//Output:

35
60

 

Method Overloading

Example:

using System;
public class Edureka
{
    public static int add(int a, int b)
    {
        return a + b;
    }
    public static float add(float a, float b)
    {
        return a + b;
    }
}
public class TestMemberOverloading
{
    public static void Main()
    {
        Console.WriteLine(Edureka.add(12, 23));
        Console.WriteLine(Edureka.add(12.4f, 21.3f));
    }
}

//Output:

35
33.699997

 

Overriding

Overriding is a situation where child class defines the same method which the parent is defining as well. Let us understand this through a small example.

Example:

using System;
public class Edureka
{
    public virtual void eat()
    {
        Console.WriteLine("Eating ");
    }
}
public class Dog : Edureka
{
    public override void eat()
    {
        Console.WriteLine("Eating food");
    }
}
public class Overriding
{
    public static void Main()
    {
        Dog d = new Dog();
        d.eat();
    }
}

//Output:

Eating food

 

Namespace

The namespace is basically used to handle multiple classes present in the program. The namespace is available in different ways.

Example:

using System;
using First;
using Second;
namespace First
{
    public class Edureka
    {
        public void sayWelcome() { Console.WriteLine("Welcome To Edureka"); }
    }
}
namespace Second
{
    public class Happy_Learning
    {
        public void sayWishes() { Console.WriteLine("Happy Learning"); }
    }
}
public class Namespace
{
    public static void Main()
    {
        Edureka h1 = new Edureka();
        Happy_Learning w1 = new Happy_Learning();
        h1.sayWelcome();
        w1.sayWishes();
    }
}

//Output:

Welcome To Edureka
Happy Learning

 

File Operations

The file operations available in C# are as follows:

OperationDescription
 BinaryReaderReads primitive data from a binary stream.
 BinaryWriterWrites primitive data in binary format.
 BufferedStreamTemporary storage for a stream of bytes.
 DirectoryHelps in manipulating a directory structure.
DirectoryInfoUsed for performing operations on directories.
 DriveInfoProvides information for the drives.
 FileHelps in manipulating files.
 FileInfoUsed for performing operations on files.
 FileStreamUsed to read from and write to any location in a file.
MemoryStream Used for random access to streamed data stored in memory.
 PathPerforms operations on path information.
 StreamReaderUsed for reading characters from a byte stream.
 StreamWriterIs used for writing characters to a stream.
 StringReaderIs used for reading from a string buffer.
 StringWriterIs used for writing into a string buffer.

FileMode

The FileMode is an enumerator which defines multiple file opening methods. The members of the FileMode Enumerator are described as follows:

FileAccess

FileAccess Enumerator is used to gaining access to a particular file. It has the following members.

FileShare

The Fileshare Enumerator is used to share a particular file. It has the following members.

 

Events

An Event is generally known as an action that is generated by the user. It might be a click of the mouse and even a single keystroke from the keyboard. Similarly, C# programs also have events. The generator of the event is called the publisher and the receiver of the event is called the subscriber.

Publisher

publisher contains the definition of the event and the delegate. The event-delegate association is defined in this object. A publisher class object invokes the event and it is notified to other objects.

Subscriber

subscriber accepts the event and provides an event handler. The delegate in the publisher class invokes the method /event handler of the subscriber class.

Example:

using System;

namespace Edureka
{
       public delegate string Del(string str);
       class EventBlock
       {
              event Del NewEvent;
              public EventBlock()
              {
                    this.NewEvent += new Del(this.WelcomeUser);
              }
              public string WelcomeUser(string username)
              {
                    return "Welcome To Edureka. " + username;
              }
              static void Main(string[] args)
              {
                    EventBlock obj1 = new EventBlock();
                    string result = obj1.NewEvent("Happy Learning");
                    Console.WriteLine(result);
              }
        }
}

//Output:

Welcome To Edureka. Happy Learning

 

Generics

Generics is a concept of providing the members and methods of a class with place holders in Run-time. We can define Generics using <> brackets. Let us check out the following examples.

Generics in a Class

using System;
namespace Edureka
{
    class GenericClass<T>
    {
        public GenericClass(T msg)
        {
            Console.WriteLine(msg);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            GenericClass<string> gen = new GenericClass<string>("This message is from generic class");
            GenericClass<int> genI = new GenericClass<int>(123);
            GenericClass<char> getCh = new GenericClass<char>('E');
        }
    }
}

//Output:

This message is from generic class
123
E

Generics in a Method

using System;
namespace Edureka
{
    class GenericClass
    {
        public void Show<T>(T msg)
        {
            Console.WriteLine(msg);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            GenericClass genC = new GenericClass();
            genC.Show("This message is from the generic method");
            genC.Show(321);
            genC.Show('H');
        }
    }
}

//Output:

This message is from the generic method
321
H

 

Delegates

The Delegate acts as a reference to the method. Basically it’s same as a function pointer in C and C++ but far better and type-safe. The Delegate in static method encapsulates method only. While the delegate in the instance method encapsulates both method and instance. The best use of delegate is to use as an event.

Example:

using System;
delegate int Calculator(int n);
public class Edureka
{
      static int number = 25;
      public static int add(int n)
      {
            number = number + n;
            return number;
      }
      public static int mul(int n)
      {
           number = number * n;
           return number;
      }
      public static int getNumber()
      {
           return number;
      }
      public static void Main(string[] args)
      {
           Calculator c1 = new Calculator(add);
           Calculator c2 = new Calculator(mul);
           c1(20);
           Console.WriteLine("After calculator one delegate, the new Number is: " + getNumber());
           c2(3);
           Console.WriteLine("After calculator two delegate, the new Number is: " + getNumber());
      }
}

//Output:

After calculator one delegate, the new Number is: 45
After calculator two delegate, the new Number is: 135

 

Reflection

The Reflection is required to obtain the metadata in run-time. The Reference is available in System.Reflection namespace. It requires the following classes to execute.

Type class

C# Type class represents type declarations for class types, interface types, enumeration types, array types, value types

Type Properties

A list of important properties of Type classes is mentioned below.

PropertyDescription
AssemblyGets the Assembly for this type.
AssemblyQualifiedNameGets the Assembly qualified name for this type.
AttributesGets the Attributes associated with the type.
BaseTypeGets the base or parent type.
FullNameGets the fully qualified name of the type.
 IsAbstractis used to check if the type is Abstract.
 IsArrayis used to check if the type is Array.
 IsClassis used to check if the type is Class.
 IsEnumis used to check if the type is Enum.
IsInterfaceis used to check if the type is Interface.
 IsNestedis used to check if the type is Nested.
 IsPrimitiveis used to check if the type is Primitive.
 IsPointeris used to check if the type is Pointer.
 IsNotPublicis used to check if the type is not Public.
IsPublicis used to check if the type is Public.
 IsSealedis used to check if the type is Sealed.
 IsSerializableis used to check if the type is Serializable.
 MemberTypeis used to check if the type is Member type of Nested type.
 ModuleGets the module of the type.
 NameGets the name of the type.
NamespaceGets the namespace of the type.

 

 

PropertyDescription
GetConstructors()Returns all the public constructors for the Type.
GetConstructors(BindingFlags)Returns all the constructors for the Type with specified BindingFlags.
GetFields()Returns all the public fields for the Type.
GetFields(BindingFlags)Returns all the public constructors for the Type with specified BindingFlags.
GetMembers()Returns all the public members for the Type.
GetMembers(BindingFlags)  Returns all the members for the Type with specified BindingFlags.
GetMethods()Returns all the public methods for the Type.
GetMethods(BindingFlags)Returns all the methods for the Type with specified BindingFlags.
GetProperties()Returns all the public properties for the Type.
GetProperties(BindingFlags)Returns all the properties for the Type with specified BindingFlags.
GetType()Gets the current Type.
GetType(String)Gets the Type for the given name.

Reflection Examples:

Get Type

Example:

using System;
public class GetType
{
    public static void Main()
    {
        int a = 10;
        Type type = a.GetType();
        Console.WriteLine(type);
    }
}

//Output:

System.Int32

 

Get Assembly

Example:

using System;
using System.Reflection;
public class GetAssembly
{
    public static void Main()
    {
        Type t = typeof(System.String);
        Console.WriteLine(t.Assembly);
    }
}

//Output:

System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e

 

Print Type Information

Example:

using System;
using System.Reflection;
public class PrintType
{
    public static void Main()
    {
        Type t = typeof(System.String);
        Console.WriteLine(t.FullName);
        Console.WriteLine(t.BaseType);
        Console.WriteLine(t.IsClass);
        Console.WriteLine(t.IsEnum);
        Console.WriteLine(t.IsInterface);
    }
}

//Output:

True
False
False

 

Print Constructors

Example:

using System;
using System.Reflection;
public class PrintConstructors
{
    public static void Main()
   {
       Type t = typeof(System.String);
       Console.WriteLine("Constructors of {0} type...", t);
       ConstructorInfo[] ci = t.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
       foreach (ConstructorInfo c in ci)
       {
              Console.WriteLine(c);
       }
   }
}

//Output:

Constructors of System.String type...
Void .ctor(Char[])
Void .ctor(Char[], Int32, Int32)
Void .ctor(Char*)
Void .ctor(Char*, Int32, Int32)
Void .ctor(SByte*)
Void .ctor(SByte*, Int32, Int32)
Void .ctor(SByte*, Int32, Int32, System.Text.Encoding)
Void .ctor(Char, Int32)
Void .ctor(System.ReadOnlySpan`1[System.Char])

 

Print Methods

Example:

using System;
using System.Reflection;
public class PrintMethods
{
      public static void Main()
     {
         Type t = typeof(System.String);
         Console.WriteLine("Methods of {0} type...", t);
         MethodInfo[] ci = t.GetMethods(BindingFlags.Public | BindingFlags.Instance);
         foreach (MethodInfo m in ci)
         {
              Console.WriteLine(m);
         }
     }
}

//Output:

Methods of System.String type...
System.String Replace(System.String, System.String)
System.String[] Split(Char, System.StringSplitOptions)
System.String[] Split(Char, Int32, System.StringSplitOptions)
System.String[] Split(Char[])
System.String[] Split(Char[], Int32)
System.String[] Split(Char[], System.StringSplitOptions)
System.String[] Split(Char[], Int32, System.StringSplitOptions)
System.String[] Split(System.String, System.StringSplitOptions)
System.String[] Split(System.String, Int32, System.StringSplitOptions)
System.String[] Split(System.String[], System.StringSplitOptions)
System.String[] Split(System.String[], Int32, System.StringSplitOptions)......

 

Print Fields

Example:

using System;
using System.Reflection;
public class PrintFields
{
     public static void Main()
     {
          Type t = typeof(System.String);
          Console.WriteLine("Fields of {0} type...", t);
          FieldInfo[] ci = t.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);
          foreach (FieldInfo f in ci)
          {
                 Console.WriteLine(f);
          }
     }
}

//Output:

Fields of System.String type...
System.String Empty

 

Now, let us move on to some advanced C# Programming Concepts

 

Advanced C# Concepts

 

Anonymous Function

The Function that lacks a specific name is called Anonymous Functions. There are two types of Anonymous Functions available in C#

  • Lambda Expressions
  • Anonymous Methods

Example:

using System;
namespace LambdaExpressions
{
    class Edureka
    {
        delegate int Square(int num);
        static void Main(string[] args)
        {
            Square GetSquare = x => x * x;
            int j = GetSquare(25);
            Console.WriteLine("Square: " + j);
        }
    }
}

//Output:

Square: 625

 

Anonymous Methods

The anonymous method provides the same functionality as a lambda expression, except that it allows us to ignore the parameter list.

Example:

using System;
namespace AnonymousMethods
{
    class Program
    {
        public delegate void AnonymousFun();
        static void Main(string[] args)
        {
            AnonymousFun fun = delegate () {
                Console.WriteLine("This is anonymous function");
            };
            fun();
        }
    }
}

//Output:

This is anonymous function

 

Multi-Threading

Multithreading is a process where multiple threads are created and assigned for different tasks. this saves time by executing multiple jobs at a time. The multithreading class is available in System.Threading namespace.

System.Threading Namespace

The System.Threading namespace contains classes and interfaces to facilitate multithreading. It provides classes to synchronize the thread resource. A list of commonly used classes are given below:

  • Thread
  • Mutex
  • Timer
  • Monitor
  • Semaphore
  • ThreadLocal
  • ThreadPool
  • Volatile

Process and thread

The Process is actually and application and it is considered to be a heavyweight component. On the other hand, The thread is one single module of the whole application. It is lightweight compared to the process

The LifeCycle of a Thread

Each Thread has a Life Cycle. The Life Cycle of the thread is defined in System.Threading.Thread class. The following are the stages in the Life Cycle of any thread.

  • Unstarted
  • Runnable (Ready to run)
  • Running
  • Not Runnable
  • Dead

The Thread class provides the following properties and methods as follows.

Thread Properties

PropertyDescription
CurrentThreadreturns the instance of currently running thread.
IsAlivechecks whether the current thread is alive or not.
IsBackgroundTo get/set value of current thread is in the background or not.
ManagedThreadIdis used to get the unique id for the currently managed thread.
Nameis used to get or set the name of the current thread.
Priorityis used to get or set the priority of the current thread.
ThreadStateis used to return a value representing the thread state.

Thread Methods

MethodDescription
Abort()is used to terminate the thread. It raises ThreadAbortException.
Interrupt()is used to interrupt a thread which is in WaitSleepJoin state.
Join()is used to block all the calling threads until this thread terminates.
ResetAbort()is used to cancel the Abort request for the current thread.
Resume()is used to resume the suspended thread. It is obsolete.
Sleep(Int32)is used to suspend the current thread for the specified milliseconds.
Start()changes the current state of the thread to Runnable.
Suspend()suspends the current thread if it is not suspended. It is obsolete.
Yield()is used to yield the execution of the current thread to another thread.

 

Main Thread Example

using System;
using System.Threading;
public class Edureka
{
    public static void Main(string[] args)
    {
        Thread t = Thread.CurrentThread;
        t.Name = "MainThread";
        Console.WriteLine(t.Name);
    }
}

//Output:

MainThread

 

Exception Handling

The exception is an error thrown by the program in its run-time. We perform Exception-Handling in order to make our program exception free.

ExceptionDescription
System.DivideByZeroExceptionError generated by dividing a number with zero.
System.NullReferenceExceptionhandles the error generated by referencing the null object.
System.InvalidCastExceptionhandles the error generated by invalid typecasting.
System.IO.IOExceptionhandles the Input/Output errors.
System.FieldAccessExceptionError generated by invalid private/protected access.

In C#, we use 4 keywords to perform exception handling:

  • try
  • catch
  • finally, and
  • throw
Example:
using System;
public class EdurekExample
{
     public static void Main(string[] args)
     {
           try
           {
                 int a = 10;
                 int b = 0;
                 int x = a / b;
            }
            catch (Exception e) 
            { 
                 Console.WriteLine(e); 
             }
             Console.WriteLine("This message is from catch block");
       }
}

//Output:

System.DivideByZeroException: Attempted to divide by zero.
at ExExaEdurekample.Main(String[] args) in F:C# TutorialC# ProgramsConsoleApp1ConsoleApp1Program.cs:line 10
This message is from catch block

Customized Exception Example

using System;
public class InvalidAgeException : Exception
{
       public InvalidAgeException(String message): base(message)
       {
       }
}
public class Customized
{
      static void validate(int age)
      {
           if (age < 18)
           {
                  throw new InvalidAgeException("Sorry, Age is expected to be greater than 18");
           }
      }
      public static void Main(string[] args)
      {
            try
            {
                  validate(12);
            }
            catch (InvalidAgeException e) 
           { 
                  Console.WriteLine(e); 
           }
           Console.WriteLine("Catch block is being executed now.");
      }
}

//Output:

InvalidAgeException: Sorry, Age is expected to be greater than 18
at Customized.validate(Int32 age) in F:C# TutorialC# ProgramsConsoleApp1ConsoleApp1Program.cs:line 18
at Customized.Main(String[] args) in F:C# TutorialC# ProgramsConsoleApp1ConsoleApp1Program.cs:line 23
Catch block is being executed now.

Finally block example

using System;
public class FinalExecption
{
    public static void Main(string[] args)
    {
        try
        {
            int a = 10;
            int b = 0;
            int x = a / b;
        }
        catch (Exception e) { Console.WriteLine(e); }
        finally { Console.WriteLine("Finally block is executed"); }
        Console.WriteLine("Catch block is executed");
    }
}

//Output:

System.DivideByZeroException: Attempted to divide by zero.
at FinalExecption.Main(String[] args) in F:C# TutorialC# ProgramsConsoleApp1ConsoleApp1Program.cs:line 10
Finally block is executed
Catch block is executed

System Exception Signature

[SerializableAttribute]  
[ComVisibleAttribute(true)]  
public class SystemException : Exception

System Exception Constructors

ConstructorDescription
SystemException()It is used to initialize a new instance of the SystemException class.
SystemException

(SerializationInfo,StreamingContext)

It is used to initialize a new instance of the SystemException class with serialized data.
SystemException(String)It is used to initialize a new instance of the SystemException class with a specified error message.
SystemException(String,Exception)It is used to initialize a new instance of the SystemException class with a specified error message and a reference to the inner exception that is the cause of this exception.

 

System Exception Properties

PropertyDescription
DataIt is used to get a collection of key/value pairs that provide additional user-defined information about the exception.
HelpLinkIt is used to get or set a link to the help file associated with this exception.
HResultIt is used to get or set HRESULT, a coded numerical value that is assigned to a specific exception.
InnerExceptionIt is used to get the Exception instance that caused the current exception.
MessageIt is used to get a message that describes the current exception.
SourceIt is used to get or set the name of the application that causes the error.
StackTraceIt is used to get a string representation of the immediate frames on the call stack.
TargetSiteIt is used to get the method that throws the current exception.

 

System Exception Methods 

MethodsDescription
Equals(Object)It is used to check that the specified object is equal to the current object or not.
Finalize()It is used to free resources and perform cleanup operations.
GetBaseException()It is used to get root exception.
GetHashCode()It is used to get the hash code.
GetObjectData

(SerializationInfo,StreamingContext)

It is used to get object data.
GetType()It is used to get the runtime type of the current instance.
MemberwiseClone() It is used to create a shallow copy of the current Object.
ToString()It is used to create and return a string representation of the current exception.

 

System Exception Example

using System;
namespace CSharpProgram
{
    class SystemExceptionExample
    {
        static void Main(string[] args)
        {
            try
            {
                int[] arr = new int[5];
                arr[10] = 25;
            }
            catch (SystemException e)
            {
                Console.WriteLine(e);
            }
        }
    }
}

//Output:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
at CSharpProgram.SystemExceptionExample.Main(String[] args) in F:C# TutorialC# ProgramsConsoleApp1ConsoleApp1Program.cs:line 11

 

Synchronization

Synchronization may be a technique that enables only 1 thread to access the resource for a specific time. No alternative thread will interrupt until the appointed thread finishes its task.

In multithreading program, threads are allowed to access any resource for the specified execution time. Threads share resources and execute asynchronously. Accessing shared resources (data)may be an important task that generally could halt the system.we have a tendency to influence it by creating-threads in a synchronous manner.

Example Without Synchronisation

using System;
using System.Threading;
class Edureka
{
    public void PrintTable()
    {
        for (int i = 1; i <= 10; i++)
        {
            Thread.Sleep(100);
            Console.WriteLine(i);
        }
    }
}
class Program
{
    public static void Main(string[] args)
    {
        Edureka p = new Edureka();
        Thread t1 = new Thread(new ThreadStart(p.PrintTable));
        Thread t2 = new Thread(new ThreadStart(p.PrintTable));
        t1.Start();
        t2.Start();
    }
}

//Output:

1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
10
10

 

Example With Synchronisation

using System;
using System.Threading;
class Edureka
{
    public void PrintTable()
    {
        lock (this)
        {
            for (int i = 1; i <= 10; i++)
            {
                Thread.Sleep(100);
                Console.WriteLine(i);
            }
        }
    }
}
class Program
{
    public static void Main(string[] args)
    {
        Edureka p = new Edureka();
        Thread t1 = new Thread(new ThreadStart(p.PrintTable));
        Thread t2 = new Thread(new ThreadStart(p.PrintTable));
        t1.Start();
        t2.Start();
    }
}

//Output:

1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10

 

New Features

Microsoft has added many latest features to C# language some of them are mentioned below.

C# 6.0

  • Using static directive
  • Exception filters
  • Await in catch/finally blocks
  • Auto property initializers
  • Default values for getter-only properties
  • Expression-bodied members
  • Null propagator
  • String interpolation
  • Nameof operator
  • Dictionary initializer
  • Compiler-as-a-service (Roslyn)

C# 7.0

  • Pattern matching
  • Tuples
  • Deconstruction
  • Local functions
  • Digit separator
  • Binary literals
  • Ref returns and locals
  • Expression bodied constructors and finalizers
  • Expression bodied getters and setters
  • Out variables
  • Generalized async return types

C# 7.1

  • Async main
  • Default expressions

 

Interview Questions based on C#

The important interview Questions based on C# Programming Language can be found in this updated Article.

With this, we come to an end of this “C# Tutorial” article. I hope you have understood the importance of Data Structures, Syntax, functionality, and operations performed using them. Now that you have understood the basics of Programming in C# through this C# Tutorial, check out the java training provided by Edureka on many technologies like Java, Spring and many more, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe got a question for us? Mention it in the comments section of this “C# Tutorial” blog and we will get back to you as soon as possible.

BROWSE COURSES