You are on page 1of 48

C# Access Modifiers / Specifiers

C# Access modifiers or specifiers are the keywords that are used to specify accessibility or scope of variables and
functions in the C# application.

C# provides five types of access specifiers.

1. Public
2. Protected
3. Internal
4. Protected internal
5. Private

We can choose any of these to protect our data. Public is not restricted and Private is most restricted. The following
table describes about the accessibility of each.

Access Description
Specifier

Public It specifies that access is not restricted.

Protected It specifies that access is limited to the containing class or in derived class.

Internal It specifies that access is limited to the current assembly.

protected It specifies that access is limited to the current assembly or types derived from the
internal containing class.

Private It specifies that access is limited to the containing type.

Examples to check accessibility of each access specifier.

1) C# Public Access Specifier


It makes data accessible publicly. It does not restrict data to the declared block.

Example

using System;  
namespace AccessSpecifiers  
{  
    class PublicTest  
    {  
        public string name = "joseph";  
        public void Msg(string msg)  
        {  
            Console.WriteLine("Hello " + msg);  
        }  
    }  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            PublicTest publicTest = new PublicTest();  
            // Accessing public variable  
            Console.WriteLine("Hello " + publicTest.name);  
            // Accessing public function  
            publicTest.Msg("welcome");  
        }  
    }  
}  

2) C# Protected Access Specifier


It is accessible within the class and has limited scope. It is also accessible within sub class or child class, in case of
inheritance.

Example
using System;  
namespace AccessSpecifiers  
{  
    class ProtectedTest  
    {  
        protected string name = "john";  
        protected void Msg(string msg)  
        {  
            Console.WriteLine("Hello " + msg);  
        }  
    }  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            ProtectedTest protectedTest = new ProtectedTest();  
            // Accessing protected variable  
            Console.WriteLine("Hello "+ protectedTest.name);  
            // Accessing protected function  
            protectedTest.Msg("welcome");  
        }  
    }  
}  

3) C# Internal Access Specifier


The internal keyword is used to specify the internal access specifier for the variables and functions. This specifier is
accessible only within files in the same assembly.

Example
using System;  
namespace AccessSpecifiers  
{  
    class InternalTest  
    {  
        internal string name = "Shantosh Kumar";  
        internal void Msg(string msg)  
        {  
            Console.WriteLine("Hello " + msg);  
        }  
    }  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            InternalTest internalTest = new InternalTest();  
            // Accessing internal variable  
            Console.WriteLine("Hello " + internalTest.name);  
            // Accessing internal function  
            internalTest.Msg("welcome");  
        }  
    }  
}  

4) C# Protected Internal Access Specifier


Variable or function declared protected internal can be accessed in the assembly in which it is declared. It can also
be accessed within a derived class in another assembly.

Example
using System;  
namespace AccessSpecifiers  
{  
    class InternalTest  
    {  
        protected internal string name = "Shantosh Kumar";  
        protected internal void Msg(string msg)  
        {  
            Console.WriteLine("Hello " + msg);  
        }  
    }  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            InternalTest internalTest = new InternalTest();  
            // Accessing protected internal variable  
            Console.WriteLine("Hello " + internalTest.name);  
            // Accessing protected internal function  
            internalTest.Msg("welcome");  
        }  
    }  
}  

5) C# Private Access Specifier


Private Access Specifier is used to specify private accessibility to the variable or function. It is most restrictive and
accessible only within the body of class in which it is declared.

Example
using System;  
namespace AccessSpecifiers  
{  
    class PrivateTest  
    {  
        private string name = "Shantosh Kumar";  
        private void Msg(string msg)  
        {  
            Console.WriteLine("Hello " + msg);  
        }  
    }  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            PrivateTest Test = new PrivateTest();  
            // Accessing private variable  
            Console.WriteLine("Hello " + Test.name);  
            // Accessing private function  
            privateTest.Msg("Peter Decosta");  
        }  
    }  
}  

C# Encapsulation
Encapsulation is the concept of wrapping data into a single unit. It collects data members and member functions into
a single unit called class. The purpose of encapsulation is to prevent alteration of data from outside. This data can
only be accessed by getter functions of the class.

A fully encapsulated class has getter and setter functions that are used to read and write data. This class does not
allow data access directly.

Here, we are creating an example in which we have a class that encapsulates properties and provides getter and setter
functions.

Example
namespace AccessSpecifiers  
{  
    class Student  
    {  
        // Creating setter and getter for each property  
        public string ID { get; set; }  
        public string Name { get; set; }  
        public string Email { get; set; }  
    }  
}  
using System;  
namespace AccessSpecifiers  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            Student student = new Student();  
            // Setting values to the properties  
            student.ID = "101";  
            student.Name = "Mohan Ram";  
            student.Email = "mohan@example.com";  
            // getting values  
            Console.WriteLine("ID = "+student.ID);  
            Console.WriteLine("Name = "+student.Name);  
            Console.WriteLine("Email = "+student.Email);  
        }  
    }  }
C# Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is a greek word. In
object-oriented programming, we use 3 main concepts: inheritance, encapsulation and polymorphism.

There are two types of polymorphism in C#:

 Compile time polymorphism

 Runtime polymorphism.

Compile time polymorphism is achieved by method overloading and operator overloading in C#. It is also known as
static binding or early binding.

Runtime polymorphism in achieved by method overriding which is also known as dynamic binding or late binding.

C# Runtime Polymorphism Example

Example of runtime polymorphism in C#.

using System;  
public class Animal{  
    public virtual void eat(){  
        Console.WriteLine("eating...");  
    }  
}  
public class Dog: Animal  
{  
    public override void eat()  
    {  
        Console.WriteLine("eating bread...");  
    }  
      
}  
public class TestPolymorphism  
{  
    public static void Main()  
    {  
        Animal a= new Dog();  
        a.eat();  
    }  
}  
C# Runtime Polymorphism Example 2

Example of runtime polymorphism in C# where we are having two derived classes.

using System;  
public class Shape{  
    public virtual void draw(){  
        Console.WriteLine("drawing...");  
    }  
}  
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 TestPolymorphism  
{  
    public static void Main()  
    {  
        Shape s;  
        s = new Shape();  
        s.draw();  
        s = new Rectangle();  
        s.draw();  
        s = new Circle();  
        s.draw();  
  
    }  
}  
C# Member Overloading
If we create two or more members having same name but different in number or type of parameter, it is known as
member overloading. In C#, we can overload:

o methods,
o constructors, and
o indexed properties

It is because these members have parameters only.

C# Method Overloading
Having two or more methods with same name but different in parameters, is known as method overloading in C#.

The advantage of method overloading is that it increases the readability of the program because you don't need to
use different names for same action.

You can perform method overloading in C# by two ways:

1. By changing number of arguments


2. By changing data type of the arguments

C# Method Overloading Example: By changing no. of arguments

Example of method overloading where we are changing number of arguments of add() method.

using System;  
public class Cal{  
    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(Cal.add(12, 23));  
        Console.WriteLine(Cal.add(12, 23, 25));  
    }  
}  
C# Member Overloading Example: By changing data type of arguments

Example of method overloading where we are changing data type of arguments.

using System;  
public class Cal{  
    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(Cal.add(12, 23));  
        Console.WriteLine(Cal.add(12.4f,21.3f));  
    }  
}  

C# Method Overriding
If derived class defines same method as defined in its base class, it is known as method overriding in C#. It is used to
achieve runtime polymorphism. It enables you to provide specific implementation of the method which is already
provided by its base class.

To perform method overriding in C#, you need to use virtual keyword with base class method and override keyword
with derived class method.

C# Method Overriding Example


Example of method overriding in C#. In this example, we are overriding the eat() method by the help of override
keyword.

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

C# Inheritance
In C#, inheritance is a process in which one object acquires all the properties and behaviors of its parent object
automatically. In such way, you can reuse, extend or modify the attributes and behaviors which is defined in other
class.

In C#, the class which inherits the members of another class is called derived class and the class whose members are
inherited is called base class. The derived class is the specialized class for the base class.

Advantage of C# Inheritance

Code reusability: Now you can reuse the members of your parent class. So, there is no need to define the member
again. So less code is required in the class.

Types of Inheritance:

 Single Inheritance

 Multilevel Inheritance

 Multiple Inheritance

 Hierarchical Inheritance.

C# Single Level Inheritance

When one class inherits another class, it is known as single level inheritance.
Example of single level inheritance which inherits the fields only.

using System;  
   public class Employee  
    {  
       public float salary = 40000;  
   }  
   public class Programmer: Employee  
   {  
       public float bonus = 10000;  
   }  
   class TestInheritance{  
       public static void Main(string[] args)  
        {  
            Programmer p1 = new Programmer();  
  
            Console.WriteLine("Salary: " + p1.salary);  
            Console.WriteLine("Bonus: " + p1.bonus);  
  
        }  
    }  

C# Single Level Inheritance Example: Inheriting Methods


Example of inheritance in C# which inherits methods only.

using System;  
   public class Animal  
    {  
       public void eat() { Console.WriteLine("Eating..."); }  
   }  
   public class Dog: Animal  
   {  
       public void bark() { Console.WriteLine("Barking..."); }  
   }  
   class TestInheritance2{  
       public static void Main(string[] args)  
        {  
            Dog d1 = new Dog();  
            d1.eat();  
            d1.bark();  
        }  
    }  

C# Multi Level Inheritance Example


When one class inherits another class which is further inherited by another class, it is known as multi level inheritance

in C#. Inheritance is transitive so the last derived class acquires all the members of all its base classes.

Example of multi level inheritance in C#.

using System;  
   public class Animal  
    {  
       public void eat() { Console.WriteLine("Eating..."); }  
   }  
   public class Dog: Animal  
   {  
       public void bark() { Console.WriteLine("Barking..."); }  
   }  
   public class BabyDog : Dog  
   {  
       public void weep() { Console.WriteLine("Weeping..."); }  
   }  
   class TestInheritance2{  
       public static void Main(string[] args)  
        {  
            BabyDog d1 = new BabyDog();  
            d1.eat();  
            d1.bark();  
            d1.weep();  
        }  
    }  

C# Hierarchical Inheritance.

More than one class is inherited from the base class in Hierarchical Inheritance.

he following the complete example of implementing Hierarchical Inheritance in C# −

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Inheritance {
   class Test {
      static void Main(string[] args) {
         Father f = new Father();
         f.display();
         Son s = new Son();
         s.display();
         s.displayOne();
         Daughter d = new Daughter();
         d.displayTwo();
         Console.ReadKey();
      }
      class Father {
         public void display() {
            Console.WriteLine("Display...");
         }
      }
      class Son : Father {
         public void displayOne() {
            Console.WriteLine("Display One");
         }
      }
      class Daughter : Father {
         public void displayTwo() {
            Console.WriteLine("Display Two");
         }
      }
   }
}
C# Multiple inheritance

For example,

public interface IA //ineterface  1    

{  

    string setImgs(string a);  

}  

public interface IB  //Interface 2    

{  

    int getAmount(int Amt);  

}  

public class ICar : IA, IB //implementatin    

{  

    public int getAmount(int Amt)  

    {  

        return 100;  

    }  
    public string setImgs(string a)  

    {  

        return "this is the car";  

    }  

}    

C# Delegates
In C#, delegate is a reference to the method. It works like function pointer in C and C++. But it is objected-oriented,
secured and type-safe than function pointer.

For static method, delegate encapsulates method only. But for instance method, it encapsulates method and instance
both.

The best use of delegate is to use as event.

Internally a delegate declaration defines a class which is the derived class of System.Delegate.

C# Delegate Example
Example of delegate in C# which calls add() and mul() methods.

using System;  
delegate int Calculator(int n);//declaring delegate  
      
public class DelegateExample  
{  
    static int number = 100;  
    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);//instantiating delegate  
        Calculator c2 = new Calculator(mul);  
        c1(20);//calling method using delegate  
        Console.WriteLine("After c1 delegate, Number is: " + getNumber());  
        c2(3);  
        Console.WriteLine("After c2 delegate, Number is: " + getNumber());  
  
    }  
}  

C# Anonymous Functions
Anonymous function is a type of function that does not has name. In other words, we can say that a
function without name is known as anonymous function.

In C#, there are two types of anonymous functions:

o Lambda Expressions
o Anonymous Methods

C# Lambda Expressions

Lambda expression is an anonymous function which we can use to create delegates. We can use lambda
expression to create local functions that can be passed as an argument. It is also helpful to write LINQ
queries.

C# Lambda Expression Syntax

(input-parameters) => expression  

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

C# Anonymous Methods
Anonymous method provides the same functionality as lambda expression, except that it allows us to
omit parameter list. Let see an example.

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();  
        }  
    }  
}  

C# Abstract
Abstract classes are the way to achieve abstraction in C#. Abstraction in C# is the process to hide the
internal details and showing functionality only.
Abstraction can be achieved by two ways:

1. Abstract class
2. Interface

Abstract class and interface both can have abstract methods which are necessary for abstraction.

Abstract Method
A method which is declared abstract and has no body is called abstract method. It can be declared inside the abstract
class only. Its implementation must be provided by derived classes. For example:

1. public abstract void draw();  

You can't use static and virtual modifiers in abstract method declaration.

C# Abstract class
In C#, abstract class is a class which is declared abstract. It can have abstract and non-abstract methods. It
cannot be instantiated. Its implementation must be provided by derived classes. Here, derived class is
forced to provide the implementation of all the abstract methods.

Example of abstract class in C# which has one abstract method draw(). Its implementation is provided by
derived classes: Rectangle and Circle. Both classes have different implementation.

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();  
    }  
}  

C# Interface
Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are declared inside the
interface are abstract methods. It cannot have method body and cannot be instantiated.

It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve fully
abstraction because it cannot have method body.

Its implementation must be provided by class or struct. The class or struct which implements the interface, must
provide the implementation of all the methods declared inside the interface.

C# interface example

Example of interface in C# which has draw() method. Its implementation is provided by two classes:
Rectangle and Circle.

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();  
    }  
}

C# Exception Handling
Exception Handling in C# is a process to handle runtime errors. We perform exception handling so that normal flow of
the application can be maintained even after runtime errors.

In C#, exception is an event or object which is thrown at runtime. All exceptions the derived
from System.Exception class. It is a runtime error which can be handled. If we don't handle the exception, it prints
exception message and terminates the program.

Advantage

It maintains the normal flow of the application. In such case, rest of the code is executed event after exception.

C# Exception Classes
All the exception classes in C# are derived from System. Exception class.

C# common exception classes:

Exception Description

System.DivideByZeroException handles the error generated by dividing a number with zero.

System.NullReferenceException handles the error generated by referencing the null object.

System.InvalidCastException handles the error generated by invalid typecasting.

System.IO.IOException handles the Input Output errors.


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

o try
o catch
o finally, and
o throw

C# try/catch
In C# programming, exception handling is performed by try/catch statement. The try block in
C# is used to place the code that may throw exception. The catch block is used to handled the
exception. The catch block must be preceded by try block.

C# example without try/catch

using System;  
public class ExExample  
{  
    public static void Main(string[] args)  
    {  
        int a = 10;  
        int b = 0;  
        int x = a/b;    
        Console.WriteLine("Rest of the code");  
    }  
}  

C# try/catch example
using System;  
public class ExExample  
{  
    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("Rest of the code");  
    }  
}  

C# Collections
In C#, collection represents group of objects. By the help of collections, we can perform various operations on objects
such as

 store object
 update object
 delete object
 retrieve object
 search object, and
 sort object

In sort, all the data structure work can be performed by C# collections.

We can store objects in array or collection. Collection has advantage over array. Array has size limit but objects
stored in collection can grow or shrink dynamically.

Types of Collections in C#
There are 3 ways to work with collections. The three namespaces are given below:

o System.Collections.Generic classes
o System.Collections classes

The System.Collections.Generic namespace has following classes:

o List
o Stack
o Queue
o LinkedList
o HashSet
o Dictionary
System.Collections classes

These classes are legacy. It is suggested now to use System.Collections.Generic classes. The System.Collections
namespace has following classes:

o ArrayList
o Stack
o Queue
o Hashtable

C# List<T> example

Example of generic List<T> class that stores elements using Add() method and iterates the list using for-each loop.

using System;  
using System.Collections.Generic;  
  
public class ListExample  
{  
    public static void Main(string[] args)  
    {  
        // Create a list of strings  
        var names = new List<string>();  
        names.Add("Sonoo Jaiswal");  
        names.Add("Ankit");  
        names.Add("Peter");  
        names.Add("Irfan");  
  
        // Iterate list element using foreach loop  
        foreach (var name in names)  
        {  
            Console.WriteLine(name);  
        }  
    }  
}  
C# HashSet<T>
C# HashSet class can be used to store, remove or view elements. It does not store duplicate elements. It is suggested
to use HashSet class if you have to store only unique elements. It is found in System.Collections.Generic namespace.

C# HashSet<T> example

Example of generic HashSet<T> class that stores elements using Add() method and iterates elements using for-each
loop.

using System;  
using System.Collections.Generic;  
  
public class HashSetExample  
{  
    public static void Main(string[] args)  
    {  
        // Create a set of strings  
        var names = new HashSet<string>();  
        names.Add("Sonoo");  
        names.Add("Ankit");  
        names.Add("Peter");  
        names.Add("Irfan");  
        names.Add("Ankit");//will not be added  
          
        // Iterate HashSet elements using foreach loop  
        foreach (var name in names)  
        {  
            Console.WriteLine(name);  
        }  
    }  
}  

C# Stack<T>
C# Stack<T> class is used to push and pop elements. It uses the concept of Stack that arranges elements in LIFO (Last
In First Out) order. It can have duplicate elements. It is found in System.Collections.Generic namespace.

C# Stack<T> example

Example of generic Stack<T> class that stores elements using Push() method, removes elements using Pop() method
and iterates elements using for-each loop.

using System;  
using System.Collections.Generic;  
  
public class StackExample  
{  
    public static void Main(string[] args)  
    {  
        Stack<string> names = new Stack<string>();  
        names.Push("Sonoo");  
        names.Push("Peter");  
        names.Push("James");  
        names.Push("Ratan");  
        names.Push("Irfan");  
  
        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());  
  
    }  
}  

C# Queue<T>
C# Queue<T> class is used to Enqueue and Dequeue elements. It uses the concept of Queue that arranges elements
in FIFO (First In First Out) order. It can have duplicate elements. It is found in System.Collections.Generic namespace.

C# Queue<T> example

Example of generic Queue<T> class that stores elements using Enqueue() method, removes elements using
Dequeue() method and iterates elements using for-each loop.

using System;  
using System.Collections.Generic;  
  
public class QueueExample  
{  
    public static void Main(string[] args)  
    {  
        Queue<string> names = new Queue<string>();  
        names.Enqueue("Sonoo");  
        names.Enqueue("Peter");  
        names.Enqueue("James");  
        names.Enqueue("Ratan");  
        names.Enqueue("Irfan");  
  
        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());  
    }  
}  

C# Dictionary<TKey, TValue>
C# Dictionary<TKey, TValue> class uses the concept of hashtable. It stores values on the basis of key. It contains
unique keys only. By the help of key, we can easily search or remove elements. It is found in
System.Collections.Generic namespace.

C# Dictionary<TKey, TValue> example

Example of generic Dictionary<TKey, TValue> class that stores elements using Add() method and iterates elements
using for-each loop. Here, we are using KeyValuePair class to get key and value.

using System;  
using System.Collections.Generic;  
  
public class DictionaryExample  
{  
    public static void Main(string[] args)  
    {  
        Dictionary<string, string> names = new Dictionary<string, string>();  
        names.Add("1","Sonoo");  
        names.Add("2","Peter");  
        names.Add("3","James");  
        names.Add("4","Ratan");  
        names.Add("5","Irfan");  
  
        foreach (KeyValuePair<string, string> kv in names)  
        {  
            Console.WriteLine(kv.Key+" "+kv.Value);  
        }  
    }  
}  
We used the DateTime when there is a need to work with the dates and times in C#.

We can format the date and time in different formats by the properties and methods of the DateTime./p>

The value of the DateTime is between the 12:00:00 midnight, January 1 0001 and 11:59:59 PM, December 31, 9999
A.D.

Here we will explain how to create the DateTime in C#.

We have different ways to create the DateTime object. A DateTime object has Time, Culture, Date, Localization,
Milliseconds.

class Program
{
static void Main(string[] args)
{
DateTime dt1;
dt1 = Convert.ToDateTime("7/16/2009 6:23 PM");
DateTime dt2 = DateTime.Now;
//display dates
Console.WriteLine("dt1 is: " + dt1.ToString());
Console.WriteLine("dt2 is: " + dt2.ToString());
//display individual values
Console.WriteLine("\nIndividual values of dt2:");
Console.WriteLine("dd: " + dt2.Day);
Console.WriteLine("mm: " + dt2.Month);
Console.WriteLine("yyyy: " + dt2.Year);
Console.WriteLine("hh: " + dt2.Hour);
Console.WriteLine("mi: " + dt2.Minute);
Console.WriteLine("ss: " + dt2.Second);
Console.WriteLine("ms: " + dt2.Millisecond);

DateTime dt3 = dt2.AddDays(5);


Console.WriteLine("\ndt2 after adding 5 days: " + dt3.ToShortDateString());
DateTime dt4 = dt2.AddMonths(5);
Console.WriteLine("\ndt2 after adding 5 months: " + dt4.ToShortDateString());
DateTime dt5 = dt2.AddYears(5);
Console.WriteLine("\ndt2 after adding 5 years: " + dt5.ToShortDateString());
DateTime dt6 = dt2.AddHours(5);
Console.WriteLine("\ndt2 after adding 5 hours: " + dt6.ToLongTimeString());
DateTime dt7 = dt2.AddMinutes(5);
Console.WriteLine("\ndt2 after adding 5 minutes: " + dt7.ToLongTimeString());
DateTime dt8 = dt2.AddSeconds(5);
Console.WriteLine("\ndt2 after adding 5 seconds: " + dt8.ToLongTimeString());
//check whether this is leap year or no
if (DateTime.IsLeapYear(dt2.Year))
Console.WriteLine("\nThis is a leap year.");
else
Console.WriteLine("\nThis is not a leap year.");
//get the total no. of days in this month
Console.WriteLine("\nNo. of days in this month: " +
DateTime.DaysInMonth(dt2.Year,
dt2.Month));
//date comparision
if (dt1 == dt2)
Console.WriteLine("\ndt1 and dt2 are equal.");
else if (dt1 > dt2)
Console.WriteLine("\ndt1 is greater than dt2.");
else if (dt1 < dt2)
Console.WriteLine("\ndt1 is less than dt2.");

TimeSpan ts = dt2 - dt1;


Console.WriteLine("\nThe difference between dt2 and dt1 is: " + ts.Days + " days.");
}
}
}

C# Multithreading
Multithreading in C# is a process in which multiple threads work simultaneously. It is a process to achieve
multitasking. It saves time because multiple tasks are being executed at a time. To create multithreaded application in
C#, we need to use System.Threding namespace.

C# Threading Example: static method


We can call static and non-static methods on the execution of the thread. To call the static and non-static methods,
you need to pass method name in the constructor of ThreadStart class. For static method, we don't need to create the
instance of the class. You can refer it by the name of class.

using System;  
using System.Threading;  
public class MyThread  
{  
    public static void Thread1()  
    {  
        for (int i = 0; i < 10; i++)  
        {  
            Console.WriteLine(i);  
        }  
    }  
}  
public class ThreadExample  
{  
    public static void Main()  
    {  
        Thread t1 = new Thread(new ThreadStart(MyThread.Thread1));  
        Thread t2 = new Thread(new ThreadStart(MyThread.Thread1));  
        t1.Start();  
        t2.Start();  
    }  
}  

C# Threading Example: non-static method


For non-static method, you need to create instance of the class so that you can refer it in the constructor of
ThreadStart class.

using System;  
using System.Threading;  
public class MyThread  
{  
    public void Thread1()  
    {  
        for (int i = 0; i < 10; i++)  
        {  
            Console.WriteLine(i);  
        }  
    }  
}  
public class ThreadExample  
{  
    public static void Main()  
    {  
        MyThread mt = new MyThread();  
        Thread t1 = new Thread(new ThreadStart(mt.Thread1));  
        Thread t2 = new Thread(new ThreadStart(mt.Thread1));  
        t1.Start();  
        t2.Start();  
    }  
}  

C# Threading Example: performing different tasks on each thread


Let's see an example where we are executing different methods on each thread.

using System;  
using System.Threading;  
  
public class MyThread  
{  
    public static void Thread1()  
    {  
        Console.WriteLine("task one");  
    }  
    public static void Thread2()  
    {  
        Console.WriteLine("task two");  
    }  
}  
public class ThreadExample  
{  
    public static void Main()  
    {  
        Thread t1 = new Thread(new ThreadStart(MyThread.Thread1));  
        Thread t2 = new Thread(new ThreadStart(MyThread.Thread2));  
        t1.Start();  
        t2.Start();  
    }  
}  

C# Threading Example: Sleep() method


The Sleep() method suspends the current thread for the specified milliseconds. So, other threads get the chance to
start execution.

using System;  
using System.Threading;  
public class MyThread  
{  
    public void Thread1()  
    {  
        for (int i = 0; i < 10; i++)  
        {  
            Console.WriteLine(i);  
            Thread.Sleep(200);  
        }  
    }  
}  
public class ThreadExample  
{  
    public static void Main()  
    {  
        MyThread mt = new MyThread();  
        Thread t1 = new Thread(new ThreadStart(mt.Thread1));  
        Thread t2 = new Thread(new ThreadStart(mt.Thread1));  
        t1.Start();  
        t2.Start();  
    }  
}  

C# Threading Example: Abort() method


The Abort() method is used to terminate the thread. It raises ThreadAbortException if Abort operation is not done.

using System;  
using System.Threading;  
public class MyThread  
{  
    public void Thread1()  
    {  
        for (int i = 0; i < 10; i++)  
        {  
            Console.WriteLine(i);  
            Thread.Sleep(200);  
        }  
    }  
}  
public class ThreadExample  
{  
    public static void Main()  
    {  
        Console.WriteLine("Start of Main");  
        MyThread mt = new MyThread();  
        Thread t1 = new Thread(new ThreadStart(mt.Thread1));  
        Thread t2 = new Thread(new ThreadStart(mt.Thread1));  
  
        t1.Start();  
        t2.Start();  
        try  
        {  
            t1.Abort();  
            t2.Abort();  
        }  
        catch (ThreadAbortException tae)  
        {  
            Console.WriteLine(tae.ToString());  
        }  
        Console.WriteLine("End of Main");  
    }  
}  

C# Threading Example: Join() method


It causes all the calling threads to wait until the current thread (joined thread) is terminated or completes its task.

using System;  
using System.Threading;  
public class MyThread  
{  
    public void Thread1()  
    {  
        for (int i = 0; i < 5; i++)  
        {  
            Console.WriteLine(i);  
            Thread.Sleep(200);  
        }  
    }  
}  
public class ThreadExample  
{  
    public static void Main()  
    {  
        MyThread mt = new MyThread();  
        Thread t1 = new Thread(new ThreadStart(mt.Thread1));  
        Thread t2 = new Thread(new ThreadStart(mt.Thread1));  
        Thread t3 = new Thread(new ThreadStart(mt.Thread1));  
        t1.Start();  
        t1.Join();  
        t2.Start();  
        t3.Start();  
    }  
}  

C# Threading Example: Naming Thread


You can change or get the name of the thread by using Name property of Thread class. Let's see an example where
we are setting and getting names of the threads.

1. using System;  
using System.Threading;  
  
public class MyThread  
{  
    public void Thread1()  
    {  
        Thread t = Thread.CurrentThread;  
        Console.WriteLine(t.Name+" is running");  
    }  
}  
public class ThreadExample  
{  
    public static void Main()  
    {  
        MyThread mt = new MyThread();  
        Thread t1 = new Thread(new ThreadStart(mt.Thread1));  
        Thread t2 = new Thread(new ThreadStart(mt.Thread1));  
        Thread t3 = new Thread(new ThreadStart(mt.Thread1));  
        t1.Name = "Player1";  
        t2.Name = "Player2";  
        t3.Name = "Player3";  
        t1.Start();  
        t2.Start();  
        t3.Start();  
    }  
}  Ne

C# Thread Synchronization
Synchronization is a technique that allows only one thread to access the resource for the particular time. No other
thread can interrupt until the assigned thread finishes its task.

In multithreading program, threads are allowed to access any resource for the required execution time. Threads share
resources and executes asynchronously. Accessing shared resources (data) is critical task that sometimes may halt the
system. We deal with it by making threads synchronized.

It is mainly used in case of transactions like deposit, withdraw etc.

Advantage of Thread Synchronization


o Consistency Maintain
o No Thread Interference

C# Lock
We can use C# lock keyword to execute program synchronously. It is used to get lock for the current thread, execute
the task and then release the lock. It ensures that other thread does not interrupt the execution until the execution
finish.

C# Example: Without Synchronization


In this example, we are not using lock. This example executes asynchronously. In other words, there is context-
switching between the threads.

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

C# Thread Synchronization Example


In this example, we are using lock. This example executes synchronously. In other words, there is no context-switching
between the threads. In the output section, we can see that second thread starts working after first threads finishes its
tasks.

using System;  
using System.Threading;  
class Printer  
{  
    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)  
    {  
        Printer p = new Printer();  
        Thread t1 = new Thread(new ThreadStart(p.PrintTable));  
        Thread t2 = new Thread(new ThreadStart(p.PrintTable));  
        t1.Start();  
        t2.Start();  
    }  
}  

C# Properties
C# Properites doesn't have storage location. C# Properites are extension of fields and accessed like fields.

The Properties have accessors that are used to set, get or compute their values.

Usage of C# Properties
1. C# Properties can be read-only or write-only.
2. We can have logic while setting values in the C# Properties.
3. We make fields of the class private, so that fields can't be accessed from outside the class directly. Now we
are forced to use C# properties for setting or getting values.

C# Properties Example
using System;  
   public class Employee  
    {  
        private string name;  
  
        public string Name  
        {  
            get  
            {  
                return name;  
            }  
            set  
            {  
                name = value;  
            }  
        }  
   }  
   class TestEmployee{  
       public static void Main(string[] args)  
        {  
            Employee e1 = new Employee();  
            e1.Name = "Sonoo Jaiswal";  
            Console.WriteLine("Employee Name: " + e1.Name);  
  
        }  
    }  

Example 2:

class Student
{

private string studentname_val;


private int age_val;
//public properties
public string StudentName
{
set
{
if (value.Length <= 20)
{
Console.WriteLine("The student name is changed as " + value);
studentname_val = value;
}
else
{
Console.WriteLine("Why you are assigning two large name...?");
}
}
get
{
return studentname_val;
}
}

public int Age


{
set
{
if (value >= 18 && value <= 60)
{
Console.WriteLine("The student age is changed as " + value);
age_val = value;
}
else
{
Console.WriteLine("Why you are assigning the wrong age...?");
}
}
get
{
return age_val;
}
}
}

class Program
{
static void Main(string[] args)
{
Student stu = new Student();
stu.StudentName = "ram";
Console.WriteLine(stu.StudentName);
Console.WriteLine();
stu.Age = 25;
Console.WriteLine(stu.Age);
Console.WriteLine();
stu.StudentName = "abcdefghijklmnopqrstuvwxyz";
Console.WriteLine(stu.StudentName);
Console.WriteLine();
stu.Age = 900;
Console.WriteLine(stu.Age);
Console.Read();
}
}

C# Nullable
In C#, Nullable is a concept that allows a type to hold an additional value  null. In other words, we can make a
variable Nullable, so, it can hold additional null value. All Nullable variables are the instances of System.Nullable<T>
struct.

The concept of Nullable is useful when we deal with databases that contain elements that may not be assigned a
value.

C# provides two different ways to create Nullable types.

1. By creating System.Nullable instance,
2. By using ? operator

C# System.Nullable Example
In the following example, we are making Nullable with the help of System.Nullable namespace.

using System;  
namespace CSharpFeatures  
{  
    class NullableExample2  
    {  
        static void Main(string[] args)  
        {  
            Nullable<int> a = 10;  
            Nullable<double> d = 10.10;  
            Nullable<char> c = 'S';  
            Nullable<bool> b = false;  
            // Displaying value  
            Console.WriteLine(a.Value);  
            // assigning null values  
            a = null;  
            d = null;  
            c = null;  
            b = null;  
            // Checking, does "a" contain value ?  
            if (a.HasValue)  
            {  
                Console.WriteLine(a.Value);  
            }  
            if(a == null)  
             Console.WriteLine("It contains null value");  
        }  
    }  
}  

C# Nullable using ? Operator Example 1


There is no significant difference between using of either System.Nullable or ? operator. We can use anyone as per
our comfort.

using System;  
namespace CSharpFeatures  
{  
    class NullableExample  
    {  
        static void Main(string[] args)  
        {  
            // Integer nullable  
            int? a = 10;  
            // Float nullable  
            double? f = 10.10;  
            // Boolean nullable  
            bool? b = false;  
            // Char nullable  
            char? c = 'S';  
            // Checking value is present or not  
            if (a.HasValue)  
            {  
                Console.WriteLine(a.Value);  
            }  
            else Console.WriteLine("a contains null value");  
            // Assigning null value  
            a = null;  
            if (a.HasValue) // Checking again  
            {  
                Console.WriteLine(a.Value);  
            }  
            else Console.WriteLine("a contains null value");  
        }  
    }  
}  

C# Nullable using ? Operator Example 2

using System;  
namespace CSharpFeatures  
{  
    class NullableExample2  
    {  
        static void Main(string[] args)  
        {  
            Nullable<int> a = 10;  
            Nullable<double> d = 10.10;  
            Nullable<char> c = 'S';  
            Nullable<bool> b = false;  
            // Displaying value  
            Console.WriteLine(a.Value);  
            // assigning null values  
            a = null;  
            d = null;  
            c = null;  
            b = null;  
            // Checking, does "a" contain value ?  
            if (a.HasValue)  
            {  
                Console.WriteLine(a.Value);  
            }  
            if(a == null)  
             Console.WriteLine("It contains null value");  
        }  
    }  
}  

C# Asynchronous Method
C# asynchronous method is a special method that executes asynchronously. C# provides async modifier to make a
method asynchronous. It is used to perform asynchronous tasks.

C# await expression is used to suspend the execution of a method.

If a method which uses async modifier does not contain await expression, executes synchronously.

C# Asynchronous Method Return Types


An async method can use any one of the following return type.

o Task
o Task<TResult>
o Void (for event handlers)
o System.Threading.Tasks.ValueTask<TResult>

public async Task<int> ExampleMethodAsync()    
{    
    // statements    
}  

We can use System.Net.HttpClient, Microsoft.Azure.EventHub.Core libraries that


contain asynchronous operations.

In the following example, we are using using System.Net.Http; namespace to execute an


asynchronous task.

This namespace is not available by default, so we need to install it by using the package manager
console.

To open console, follow the instruction as we did in the following screenshot.


This will open a console window, where we can pass namespace name to install it in our project.
Write the following command, as we did in the following screenshot.

1. PM> Install-Package System.Net.Http  

After installing it, now we can execute the application.

C# Asynchronous Method Example

using System;  
using System.Threading.Tasks;  
using System.Net.Http;  
namespace CSharpFeatures  
{  
    class AsynchronousMethod  
    {  
        static void Main(string[] args)  
        {  
           Task<int> result = add();  
           Console.WriteLine("length: {0}", result.Result);  
        }  
// Asynchronous method  
        async static Task<int> add()  
        {  
            Task<string> TaskUrl = new HttpClient().GetStringAsync("http://www.Tcs.com");  
            string result = await TaskUrl;  
            return result.Length;  
        }  
    }  
}  

C# Params
In C#, params is a keyword which is used to specify a parameter that takes variable number of arguments. It is useful
when we don't know the number of arguments prior. Only one params keyword is allowed and no additional
parameter is permitted after params keyword in a function declaration.

C# Params Example 1
using System;  
namespace AccessSpecifiers  
{  
    class Program  
    {  
        // User defined function  
        public void Show(params int[] val) // Params Paramater  
        {  
            for (int i=0; i<val.Length; i++)  
            {  
                Console.WriteLine(val[i]);  
            }  
        }  
        // Main function, execution entry point of the program  
        static void Main(string[] args)  
        {  
            Program program = new Program(); // Creating Object  
            program.Show(2,4,6,8,10,12,14); // Passing arguments of variable length  
        }  
    }  
}  

C# Params Example 2

In this example, we are using object type params that allow entering any number of inputs of any type.

using System;  
namespace AccessSpecifiers  
{  
    class Program  
    {  
        // User defined function  
        public void Show(params object[] items) // Params Paramater  
        {  
            for (int i = 0; i < items.Length; i++)  
            {  
                Console.WriteLine(items[i]);  
            }     
        }  
        // Main function, execution entry point of the program  
        static void Main(string[] args)  
        {  
            Program program = new Program(); // Creating Object  
            program.Show("Ramakrishnan Ayyer","Ramesh",101, 20.50,"Peter", 'A'); // Passing arguments of variable length  
        }     
    }  
}  

The Func and Action generic delegates were introduced in the .NET Framework version 3.5.

Whenever we want to use delegates in our examples or applications, typically we use the following procedure:

 Define a custom delegate that matches the format of the method.


 Create an instance of a delegate and point it to a method.
 Invoke the method.

But, using these 2 Generics delegates we can simply eliminate the above procedure.

Action<>

 The Generic Action<> delegate is defined in the System namespace of microlib.dll


 This Action<> generic delegate; points to a method that takes up to 16 Parameters and returns void.

Func<>

 The generic Func<> delegate is used when we want to point to a method that returns a value.
 This delegate can point to a method that takes up to 16 Parameters and returns a value.
 Always remember that the final parameter of Func<> is always the return value of the method.
(For example, Func< int, int, string>, this version of the Func<> delegate will take 2 int parameters and
returns a string value.)

Create a new project named “FuncAndActionDelegates” and create a new class that holds all your methods.

MethodCollections.cs

class MethodCollections  

    {  

  

        //Methods that takes parameters but returns nothing:  

   

        public static void PrintText()  

        {  

            Console.WriteLine("Text Printed with the help of Action");  

        }  

        public static void PrintNumbers(int start, int target)  

        {  

            for (int i = start; i <= target; i++)  

            {  

                Console.Write(" {0}",i);  

            }  

            Console.WriteLine();  

        }  

        public static void Print(string message)  

        {  

            Console.WriteLine(message);  

        }  

  
        //Methods that takes parameters and returns a value:  

  

        public static int Addition(int a, int b)  

        {  

            return a + b;  

        }  

  

        public static string DisplayAddition(int a, int b)  

        {  

            return string.Format("Addition of {0} and {1} is {2}",a,b,a+b);  

        }  

  

        public static string SHowCompleteName(string firstName, string lastName)  

        {  

            return string.Format("Your Name is {0} {1}",firstName,lastName);  

        }  

        public static int ShowNumber()  

        {  

            Random r = new Random();  

            return r.Next();  

        }  

    } 

class Program  

    {  

        static void Main(string[] args)  

        {  
            Action printText = new Action(MethodCollections.PrintText);  

            Action<string> print = new Action<string>(MethodCollections.Print);  

            Action<int, int> printNumber = new Action<int, int>(MethodCollections.PrintNum
bers);  

  

            Func<int, int,int> add1 = new Func<int, int, int>(MethodCollections.Addition); 
 

            Func<int, int, string> add2 = new Func<int, int, string>(MethodCollections.Dis
playAddition);  

            Func<string, string, string> completeName = new Func<string, string, string>(M
ethodCollections.SHowCompleteName);  

            Func<int> random = new Func<int>(MethodCollections.ShowNumber);  

  

            Console.WriteLine("\n***************** Action<> Delegate Methods *************
**\n");  

            printText();    //Parameter: 0 , Returns: nothing  

            print("Abhishek");  //Parameter: 1 , Returns: nothing  

            printNumber(5, 20); //Parameter: 2 , Returns: nothing  

            Console.WriteLine();  

            Console.WriteLine("**************** Func<> Delegate Methods *****************\
n");  

            int addition = add1(2, 5);  //Parameter: 2 , Returns: int  

            string addition2 = add2(5, 8);  //Parameter: 2 , Returns: string  

            string name = completeName("Abhishek", "Yadav");    //Parameter:2 , Returns: s
tring  

            int randomNumbers = random();   ////Parameter: 0 , Returns: int  

  

            Console.WriteLine("Addition: {0}",addition);  

            Console.WriteLine(addition2);  

            Console.WriteLine(name);  
            Console.WriteLine("Random Number is: {0}",randomNumbers);  

  

            Console.ReadLine();  

        }  

    } 

Output:

You might also like