C# Part2
C# Part2
C# Access modifiers or specifiers are the keywords that are used to specify accessibility or scope of variables and
functions in the C# application.
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
Protected It specifies that access is limited to the containing class or in derived class.
protected It specifies that access is limited to the current assembly or types derived from the
internal containing class.
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");
}
}
}
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");
}
}
}
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");
}
}
}
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");
}
}
}
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 = "[email protected]";
// 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.
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.
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
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
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.
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
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.
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.
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);
}
}
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();
}
}
in C#. Inheritance is transitive so the last derived class acquires all the members of all its base classes.
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.
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.
Internally a delegate declaration defines a class which is the derived class of System.Delegate.
Types of Delegate:
class sample
{
public int getsum(int a,int b,int c)//first
{
return a + b + c;
}
}
class Program
{
delegate int sampledelegate(int a, int b, int c);//second
static void Main(string[] args)
{
sample s = new sample();
sampledelegate sd = new sampledelegate(s.getsum);//third
Console.WriteLine("My target class name" + sd.Target);
Console.WriteLine("my target method signature" + sd.Method);
Console.WriteLine("Enter a value");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter a value");
int b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter a value");
int c = Convert.ToInt32(Console.ReadLine());
int sum = sd.Invoke(a, b, c);//fourth
Console.WriteLine("sum value is" + sum);
Console.ReadLine();
}
}
}
Example of mlti cast 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# Generics
Generic is a concept that allows us to define classes and methods with placeholder. C# compiler replaces these
placeholders with specified type at compile time. The concept of generics is used to create general purpose classes
and methods.
o define generic class, we must use angle <> brackets. The angle brackets are used to declare a class or method as
generic type. In the following example, we are creating generic class that can be used to deal with any type of data.
C# Operator Overloading
Overloading is generally defined as a process of implementing popular
Object-oriented programming concepts such as Polymorphism, which means one name having different forms and
implementations. It allows the variables or the object to take different kinds of forms while executing the code. It is
mainly used when you want the method property not to be similar to the given arguments, rather want a different
order of execution when one name can be used with different types of execution methods and properties. This can be
achieved in a program with different types of parameters and their count. There are various types of operator
overloading methods in C#. You will learn all such methods in this tutorial conveniently.
public static classname operator op (parameters)
{
// Code
}
For Unary Operator
public static classname operator op (t)
{
// Code
}
For Binary Operator
public static classname operator op (t1, t2)
{
// Code
}
The operator is usually is a keyword that is used while implementing operator overloading. It is important to note
that the return type of the overloaded operator cannot be kept void. It means that while performing operator
overloading, the preference is always in the over-defined implementations' hands. There is no preference given to
predefined implementations.
Program that displays how unary operators inside a class Complex can be overloaded.
using System;
class Complex
{
private int x;
private int y;
public Complex()
{
}
public Complex(int i, int j)
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine("{0} {1}", x, y);
}
public static Complex operator -(Complex c)
{
Complex temp = new Complex();
temp.x = -c.x;
temp.y = -c.y;
return temp;
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10, 20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex();
c2.ShowXY(); // displays 0 & 0
c2 = -c1;
c2.ShowXY(); // diapls -10 & -20
}
}
Consider the following example code that shows how binary operator overloading works.
using System;
class Complex
{
private int x;
private int y;
public Complex()
}
public Complex(int i, int j)
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine("{0} {1}", x, y);
}
public static Complex operator +(Complex c1, Complex c2)
{
Complex temp = new Complex();
temp.x = c1.x + c2.x;
temp.y = c1.y + c2.y;
return temp;
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10, 20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex(20, 30);
c2.ShowXY(); // displays 20 & 30
Complex c3 = new Complex();
c3 = c1 + c2;
c3.ShowXY(); // dislplays 30 & 50
}
}
It is important to keep a note that operators such as ==. !=, <>, <=, >= are only overloaded as pairs. When a binary
arithmetic operator is overloaded using them, the assignment operators will automatically get overloaded. For
instance, if you overload the + operator, it gets implicitly overloaded as += operator too.
C# Partial Types
C# provides a concept to write source code in separate files and compile it as a single unit. This feature is called
partial types and included in C# 2.0. The partial keyword is used to create partial types.
It allows us to write partial class, interface, struct and method in two or more separate source files. All parts are
combined when the application is compiled.
Let's see an example. Here, we are creating a partial class that includes a depositeAmount() function in
the Customer.cs file and a withdraw() function in the Customer2.cs file. Both functions are stored in separate file and
combined when compiled.
using System;
namespace CSharpFeatures
{
partial class Customer
{
// Deposit function
public void depositAmount(int d_amount)
{
amount += d_amount;
Console.WriteLine(d_amount+" amount is deposited");
Console.WriteLine("Available balance is: "+amount);
}
}
}
// Customer2.cs
using System;
namespace CSharpFeatures
{
partial class Customer
{
private int amount;
public int Amount { get => amount; set => amount = value; }
// Withdraw function
public void withdraw(int w_amount)
{
amount -= w_amount;
Console.WriteLine(w_amount+" is withdrawn");
Console.WriteLine("Available balance is: "+amount);
}
}
}
Program.cs
using System;
namespace CSharpFeatures
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
customer.Amount = 2000;
Console.WriteLine("Current balance is: "+ customer.Amount);
customer.depositAmount(1000);
// Accessing seperate file function
customer.withdraw(500);
}
}
}
C# Sealed
C# sealed keyword applies restrictions on the class and method. If you create a sealed class, it cannot be derived. If
you create a sealed method, it cannot be overridden.
C# Sealed class
C# sealed class cannot be derived by any class. Let's see an example of sealed class in C#.
using System;
sealed public class Animal{
public void eat() { Console.WriteLine("eating..."); }
}
public class Dog: Animal
{
public void bark() { Console.WriteLine("barking..."); }
}
public class TestSealed
{
public static void Main()
{
Dog d = new Dog();
d.eat();
d.bark();
}
}
C# Sealed method
The sealed method in C# cannot be overridden further. It must be used with override keyword in method.
using System;
public class Animal{
public virtual void eat() { Console.WriteLine("eating..."); }
public virtual void run() { Console.WriteLine("running..."); }
}
public class Dog: Animal
{
public override void eat() { Console.WriteLine("eating bread..."); }
public sealed override void run() {
Console.WriteLine("running very fast...");
}
}
public class BabyDog : Dog
{
public override void eat() { Console.WriteLine("eating biscuits..."); }
public override void run() { Console.WriteLine("running slowly..."); }
}
public class TestSealed
{
public static void Main()
{
BabyDog d = new BabyDog();
d.eat();
d.run();
}
}
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.
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.
(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.
Exception Description
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.
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
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
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.
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.
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);
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.
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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");
}
}
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();
}
}
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.
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.
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();
}
}
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
{
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.
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");
}
}
}
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");
}
}
}
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# static class
The C# static class is like the normal class but it cannot be instantiated. It can have only static members. The
advantage of static class is that it provides you guarantee that instance of static class cannot be created.
using System;
public static class MyMath
{
public static float PI=3.14f;
public static int cube(int n){return n*n*n;}
}
class TestMyMath{
public static void Main(string[] args)
{
Console.WriteLine("Value of PI is: "+MyMath.PI);
Console.WriteLine("Cube of 3 is: " + MyMath.cube(3));
}
}