Tuesday, June 30, 2020

C# Tutorial 18 - Exception Handling in C#

C# Tutorial 18 - Exception Handling in C#

The main idea behind exception handling is to handle the runtime errors and prevent program from being crash. An unhandled exception in code results in crashing of the code. For example, if you are performing division of two variable and if divisor is zero then an exception raised. Another example can be of accessing a file which does not exists on file system. Exception terminates the normal flow of application as it terminates the application. Exception handling allows to continue normal flow of application by handling the exception. In .NET framework, there are numerous classes available for exceptions. Exception class is base of these classes and if you are creating a new exception, it will inherit the Exception class. An example of exception is following snippet of code:

int[] arr = new arr[3];
Console.WriteLine(arr[5]);

It will generate exception of IndexOutOfRangeException. Now we will see the general syntax of Exception handling. 
try
{
    // place the code here which may raise exception
}
catch(Exception type)
{
    // handle the exception
}
finally
{
    // final code
}
try block
It contains the code which may raise the exception or is suspicious of raising an exception. If exception occurs, respective exception block will be executed.

catch block
It is the block where exception is actually handled and it requires exception object as parameter which is used for getting information about exception. If you are not sure about exact type of exception you can pass object of Exception class You can log or audit the what you want to do in order to handle the exception.

finally block
Finally block gets executed whether exception occurs or not. The main idea behind finally is to release the resources being utilized like database connection of closing the file stream.

Now exception raised in above example can be handled as follows:

          try
          {
               int x = 10;
               int y = 0;
               Console.WriteLine(x/y);
          }
          catch(Exception ex)
          {
               Console.Write(ex.Message);
          }
Now lets see an example of using finally block.
FileInfo file = null;
try
{
Console.Write("Enter a file name");
string fileName = Console.ReadLine();
file = new FileInfo(fileName);
file.AppendText("Hello There")
}
catch(Exception ex)
{
Console.WriteLine(ex.Message );
}
finally
{
file = null;
}
You can also use multiple catch blocks with a single try block like example below. 
try
{
//code that may raise an exception
}
catch(DivideByZeroException ex)
{
Console.WriteLine("Division By Zero");
}
catch(InvalidOperationException ex)
{
Console.WriteLine("
Invalid Operation Performed");
}

Monday, June 29, 2020

C# Tutorial 17 - Polymorphism in C#

C# Tutorial 17 - Polymorphism in C#


Polymorphism means to take more than one form and it fourth principle concept of Object Oriented Programming. "Poly" means many and "morph" means forms. Polymorphism allows us to have multiple methods with same name in a class and then to call one of these methods based on our criteria or requirements.

Types of Polymorphism

  • Static or Compile Time Polymorphism
  • Dynamic or Runtime Polymorphism

Static or Compile Time Polymorphism

Method overloading and Operator overloading are examples of static or compile time polymorphism. It is also referred as early binding. It is called compile time or static polymorphism because decision for selecting appropriate method for given requirements is taken at compile time. Number, Type and Order of parameters is checked for selection of appropriate method in method overloading. For methods, main concept in overloading is that methods with same name but different signature. Keep in mind that return type is not part of signature. We can acquire overloading of methods using three ways.
  • Number of parameters
  • Order of parameters
  • Type of parameters


public class Calculate
{
    
     public void Add(int a, int b)
{
    Console.WriteLine("a + b: "+sum);
}
          // Numbers of parameters
public void Add(int a, int b, int c)
{
    Console.WriteLine("Sum of a+b+c: "+sum);
}
// Types of parameters
public void Add(int a, double b)
{
    Console.WriteLine("Sum of a + b: "+sum);
}
// Order of parameters
public void Add(double a, int b)
{
    Console.WriteLine("Sum of a + b: "+sum);
}
}

class Program
{
    static void Main()
    {
Calculate c = new Calculate();

c.Add(1, 2);

c.Add(1, 2, 3); 

c.Add(1, 2.8593);

c.Add(32.54, 1);

Console.ReadLine();
    }
}

Dynamic or Runtime Polymorphism

The key idea behind method overriding is that, method name and parameters are same but they have different implementation as per requirements. It is also called dynamic polymorphism or late binding. Usually its done when inheritance is implemented and both Parent and Child class have method with same name. For example you have class named Vehicle which have a method with name VehicleInfo() and it displays general information of Vehicle and there is another class with name Car and this class also have a method with name VehicleInfo(), then definition of method VehicleInfo() in Vehicle class will be override by method in Car class. See example below. Hello method in Student, Employee and Human class will have its own definition and when using object of each class, each of object will call its respective class' method.

class Human

   public virtual void Hello() 
   { 
         Console.WriteLine("Hello Human");
   } 

 
class
Student: Human 

    public override
void Hello(
    { 
        Console.WriteLine("Hello Student"); 
    } 
}   
class Employee:
Human 

    public override
void Hello() 
    { 
        Console.WriteLine("Hello Human");     
    

class Program

    public static
void Main() 
    { 
        Human h = new Human();
        h.Hello();    // Output: Hello Human
        Student s = new Student();
        s.Hello();    // Output: Hello Student
        Employee e = new Employee();
        e.Hello();    // Output: Hello Employee
    




C# Tutorial 16 - Encapsulation in C#

C# Tutorial - Encapsulation in C#

In Object Oriented Programming, Encapsulation is one of the main key feature and main purpose of it is to prevent access to implementation details. In previous tutorial, we have discussed access specifiers, which are used for controlling access to fields and methods in class. So access specifiers are used for achieving encapsulation. Encapsulation allows to encapsulate data and to protect it from being modified accidentally or deliberately. Encapsulation prevents data from accidental manipulation or corruption. To achieve encapsulation, instead of declaring them public we declare them as private. These private fields are then can be modified using two ways.
  • By using Accessor & Mutator
  • By using Named Properties
By using Acessor & Mutator
class Account
{  
    private int accountnumber;
    //Accessor
    public int GetAccountNumber()
    {
        return accountnumber;
    }
    //Mutator
    public void SetAccountNumber(int value)
    {
        accountnumber = value;
    }
}
class Program {
    public static void Main()
    {
        Account a = new Account();
        a.SetAccountNumber = 123456;
        Console.WriteLine(a.GetAccountNumber);
    }
}

In above example you can see that we are accessing SetAccountNumber method also called Accessor in order to set value of field account number in Account class and we are using GetAccountNumber method also called Mutator to acquire the value of account number field in Account class.
By using Named Properties
class Account
{  
    private int accountnumber;
    //Named Property
    public int AccountNumber()
    {
        get { return accountnumber; }
        set {
accountnumber = value; }            
    }
}
class Program {
    public static void Main()
    {
        Account a = new Account();
        a.AccountNumber = 123456;
        Console.WriteLine(a.AccountNumber);
    }
}
In this example, we have used properties in order to access private fields with get and set methods for 
accessing private field of class Account.


Sunday, June 28, 2020

C# Tutorial 15 - Inheritance in C#

C# Tutorial 15 - Inheritance in C#


 A main concept in Object Oriented Programming is inheritance. It allows us to speed up implementation time as we can reuse already existing code and allows us to inherit fields and members of another class. Instead of writing new code we look for existing code, and inherit it in our new code. C# does not supports multiple inheritance it only supports multilevel inheritance.
  • Child/Derived Class - a class that inherits another class is derived or child class.
  • Parent/Base Class - a class being inherited from is called parent or base class.
The general syntax for inheriting a class in C# is as follow:
class derived-class : base-class  
{  
   // methods and fields  
   .
   .
} 
By default members of a class are private and private members are not inherited while inheriting a class. In order to inherit members using inheritance, you can set them internal or protected internal. We have discussed access modifiers in previous tutorials.. Now, consider a class Vehicle which have three fields engine number, model and color and there is another class with name Car which is inheriting this Vehicle class
class Vehicle // Base class 
{  
   internal int engine_no;
   internal string color;
  
internal string model;
}
class Car : Vehicle // Derived class
{
    int power;
    string company;
    public void showDetails()
    {
        Console.WriteLine("Engine No.: "+engine_no);
        Console.WriteLine("Color is: "+color);
        Console.WriteLine("Model: "+model);
        Console.WriteLine("Power: "+power);
        Console.WriteLine("Engine No.: "+
company);    
    }
}
class Program    // Main Class
{
    public static void Main()
    {
        Car c1 = new Car();
        c1.engine_no = 12345;
        c1.color = "blue";
        c1.model = "Benz";
        c1.power = 2000;
        c1.company = "
Mercedes";
        c1.showDetails();
    }
}
As mentioned before, C# does not supports multiple inheritance but multilevel inheritance. If
you want to achieve multiple inheritance, you can do so by using interfaces. We will discuss
interfaces upcoming tutorials. A general example of multilevel inheritance is given below:
class A  
{  
   // methods and fields in class A
   .
   .
} 

//Inherits fields and members of class A
     class B : A  
     {  
        // methods and fields in class B 
        .
        .
     }         
     //Inherits fields and members of class B
     // and B also contains fields and members of class A
class C : B  
{  
    // methods and fields in class C
    .
    .
}



Monday, June 22, 2020

C# Tutorial 14 - Understand Abstraction In C#

Tutorial: 14 - Abstraction in C#
           
Abstraction
Exposing only information which is relevant and essential to user and hiding certain details from the user is referred as Abstraction. Abstraction can be achieved using either interfaces or abstract classes.
Example
Consider an example of ATM. A user enters his card in ATM, then enters PIN Code. After accessing the account, he enters the amount which is required by him to withdraw and lastly he gets his amount from ATM. The user doesn't know how this ATM works internally all he care is to operate the machine using touch panel or keypad on ATM. This is an example ATM machine.

Now to achieve abstraction we will use abstract class.

Abstract Class
Abstract classes are special classes marked with keyword abstract and they cannot be instantiated meaning you cannot create their objects. A method which is marked abstract does not have its implementation. In order to create an abstract class or abstract method you have to use abstract keyword e.g.

public abstract void hello();
//abstract method
public abstract Student
//abstract method

There are some points you should keep in mind for an abstract class.
  • Abstract classes are only inherited and you have to provide implementation of inherited method available in abstract class..
  • A user must use the override keyword before the method which is declared as abstract in child class, the abstract class is used to inherit in the child class.
  • Structures cannot inherit abstract classes.
  • There are no constructors or destructors in abstract classes
  • You can add a non abstract method in it and provide its implementation.
  • It does not supports multiple inheritance.
  • It cannot be static.
  • If all the methods in a class are abstract, then class is called pure abstract class.
  • You cannot set an abstract class as sealed class.
Now we will see an example how to implement abstraction in C#
public abstract class Human
{ 
    public abstract void hello();
    //Abstract Method 
}
  
// Student class inheriting Human class
public class Student : Human
{ 
    // Overriding method using override keyword
    public override void hello()
    {
        Console.WriteLine("In Student class");
    }
}
public class Employee : Human
{
    // Overriding method using override keyword
    public override void hello()
    {
        Console.WriteLine("In Employee class");
    }
}
public static void main()
{
    Student s = new Student();
    s.hello();
    Employee e = new Employee();
    e.hello();
}
Output:    
In Student class
In Employee class

In above program, we have created a class named Human and there are other two classes with name Student and Employee. Both classes are inheriting Human class and then they are implementing the method hello with each class having its own implementation. Keep in mind that abstract classes can also work with get and set methods.

C# Tutorial: 13 - Object Oriented Programming

Tutorial: 13 - Object Oriented Programming (OOP)

Object Oriented Programming is backbone of .NET framework. The key idea behind Object Oriented Programming is to create classes and objects which contains fields and methods. There are several advantages to object oriented programming:

  • It is faster and easier to execute
  • It provides clear structure for the programs
  • It helps to makes the code easier to maintain, modify and debug
  • It helps to create reusable applications.
The four pillars of Object Oriented Programming are:
  • Abstraction
  • Inheritance
  • Polymorphism
  • Encapsulation
Abstraction
Exposing only information which is relevant and essential to user and hiding certain details from the user is referred as Abstraction. Abstraction can be achieved using either interfaces or abstract classes. We will discuss abstract classes and interfaces in later tutorials. For now just understand basic idea.

Inheritance
The key idea behind inheritance in to inherit the fields and methods from one class to another.  The class which inherits the fields and methods is called child/derived class and the class from which we inherit fields and methods is called parent/base class.

Polymorphism
When classes have relation among them using inheritance or they are linked with each other using inheritance, polymorphism comes in action. This allows to perform single operations with different ways.

Encapsulation
In object oriented programming, encapsulations is referred to prevention of access to implementation. Encapsulation is achieved using access specifiers which we have already discussed.

In next tutorials, we will discuss these concepts in details.

Wednesday, June 17, 2020

C# Tutorial: 12 - Access Specifiers

Tutorial: 12 - Access Specifiers
Access specifiers are used for controlling the access of members of class. There are 5 types of access specifiers in C#.
  1. Private
  2. Public
  3. Internal
  4. Protected
  5. Protected Internal
Private
It is used for limiting access of members within the class or types for example if members of a class are private then you can access only within the class not outside the class. By default if no access specifier is used, class members are private.

Public
If members or types are declared public, then these can be accessed outside class, inside assembly or even outside of assembly.

Internal
When you want to allow access of members or types within the assembly, you need to set them as internal so these will be accessible within the assembly in .NET framework.

Protected
Protected is used when use of inheritance is required, Using protected as access specifier will allow members to be accessible in child class.

Protected Internal
Using the protected internal will result in combined effect of both protected and internal. Members will be accessible within the assembly as well as with usage of inheritance.


Thursday, June 11, 2020

C# Tutorial: 11 - Handling User Input in C#

Tutorial: 11 - Handling User Input in C#
In C#, like other programming languages, you can take input from user for processing it.
C# provides three methods for taking input from user in Console Applications.

Console.Read()
    It reads characters from input stream and then returns respective ASCII value. Also keep in mind that return type will be integer as ASCII is stored using integer data type. See following snippet:

int i = Console.Read();    // Input:  6   
Console.WriteLine(i);      // Output: 54

Console.ReadLine()
    It reads all characters from input stream till user presses Enter from keyboard and returns a string.  See following snippet:

string s = Console.ReadLine(); // Input: Hello  
Console.WriteLine(s);          // Output: Hello

Since readline returns a string when you want to perform on integer or floating point values you will need to Cast string into respective data type:

int i;
i = Convert.ToInt32(Console.ReadLine()); // Input: 12
Console.WriteLine(i);                    // Output: 12

double d;
d = Convert.ToDouble(Console.ReadLine()); // Input: 1.2 Console.WriteLine(d);                     // Output: 1.2

Console.ReadKey()
    It reads the character input by the user and returns its name. See following snippet:

ConsoleKeyInfo k = Console.ReadKey(); // Input:  a
Console.WriteLine(k.KeyChar);         // Output: a
Console.WriteLine(k.Key);             // Output: A

Monday, May 25, 2020

C# Tutorial: 10 - Classes in C#

Tutorial 10: Classes & Objects

As you know C# is an Object Oriented Programming Language, so things are associated with classes and objects with attributes and methods included. For example a Keyboard's attributes include Type, Color etc and methods include KeyPress, KeyUp, KeyDown etc. When you define a class you are actually defining what your data will be and what type of methods you can perform on that specific data type. Objects are instances of a class. When a class is declared, there is no memory assigned to objects. Memory is assigned as soon as object of a class is created.

Declaring Classes

A class is declared using class keyword in C#. The general syntax for creating a class can be as follow:
//Access modifier - class - class identifier
public class Vehicle
{
// Properties,
Fields, Methods and Events
}
where Vehicle is class name.

Adding fields to a Class

Variables which are declared and used in a class are referred as fields. These fields can be of any 
data types available in C#. If you specify no access modifier before field it will be internal.
We will discuss access modifier in next tutorial. Below is an example how can you add fields
to a class.
public class Vehicle
{    
    int no_of_wheels;
    string color;
    int engine_no;
}
In above example, there are three fields, two of integer type and one of string type.

Adding methods to a Class

You can also add methods to a class. Methods in class defines how an object/instance of class will behave.
public class Vehicle
{    
    int no_of_wheels;
    string color;
    int engine_no;
    public void VehicleInfo()
    {
        Console.WriteLine("Color of Vehicle is"+color);
        Console.WriteLine("No of Wheels, in vehicle are "+no_of_wheels);
        Console.WriteLine("Engine No. of Vehicle is"+engine_no);
    }
}

Creating an Object

A class and objects are two different things. A Class is actually defining an object whereas an object is an instance of a class. When you create an instance reference of class is returned to the used for example in example below v1 holds the reference of Vehicle instance. You can create an object by using new keyword:
Vehicle v1 = new Vehicle();

Accessing Class Members

You can access members of a class using . (dot) operator.
Vehicle v1 = new Vehicle();
Console.WriteLin(v1.color);
v1.VehicleInfo();

Here is complete example of above code.

Output of above code will be:
Vehicle Color is: Blue
Engine No is: 1234
No. of wheels in Vehicle are: 4
In next tutorial we will discuss access modifiers.