2. Operator Overloading
The concept of overloading a function can also
be applied to operators. Operator overloading
gives the ability to use the same operator to do
various operations. It provides additional
capabilities to C# operators when they are
applied to user-defined data types. It enables to
make user-defined implementations of various
operations where one or both of the operands
are of a user-defined class.
4. Overloading ability of the various
operators
OPERATORS DESCRIPTION
+, -, !, ~, ++, – –
unary operators take one operand and
can be overloaded.
+, -, *, /, %
Binary operators take two operands
and can be overloaded.
==, !=, =
Comparison operators can be
overloaded.
&&, ||
Conditional logical operators cannot
be overloaded directly
+=, -+, *=, /=, %=, =
Assignment operators cannot be
overloaded.
5. //WAP to change the sign using unary operatot
class Calculator
{
public int number1;
public Calculator(int num1)
{
number1 = num1;
}
// Function to perform operation
// By changing sign of integers
public static Calculator operator -(Calculator c1)
{
c1.number1 = -c1.number1;
Console.WriteLine("From class"+c1.number1);
return c1;
}
}
class Program
{
static void Main(string[] args)
{
Calculator calc = new Calculator(15);
calc = -calc;
Console.ReadKey();
}
}
6. uing System;
namespace BinaryOverload
{
class Calculator
{
public int number = 0;
public Calculator()
{
}
public Calculator(int n)
{
number = n;
}
// Overloading of Binary "+" operator
public static Calculator operator +(Calculator Calc1,Calculator Calc2)
{
Calculator Calc3 = new Calculator();
Calc3.number = Calc2.number + Calc1.number;
return Calc3;
}
// function to display result
public void display()
{
Console.WriteLine("{0}", number);
}
}
class CalNum
{
static void Main(string[] args)
{
Calculator num1 = new Calculator(200);
Calculator num2 = new Calculator(40);
Calculator num3 = new Calculator();
num3 = num1 + num2;
num1.display();
num2.display();
num3.display();
Console.ReadKey();
}
}
}
7. NOTE
• The return type can be of any type except void
for unary operators like !, ~, + and dot (.)
• The return type must be the type of ‘Type’ for
– and ++ operators.
8. INHERITANCE
• Acquiring (taking) the properties of one class
into another class is called inheritance.
Inheritance provides reusability by allowing us
to extend an existing class.
• The reason behind OOP programming is to
promote the reusability of code and to reduce
complexity in code and it is possible by using
inheritance.
12. NOTE
• C# do not support multiple inheritance to
aviod Ambiguity . In multiple inheritance, you
have a derived class which inherits two base
classes Diamond problem
13. • Default Superclass: Except Object class, which
has no superclass, every class has one and
only one direct superclass(single inheritance).
• Superclass can only be one: A superclass can
have any number of subclasses. But a subclass
can have only one superclass.
14. using System;
namespace ConsoleApplication1
{
// Base class
class STD
{
// data members
public string name;
public string subject;
// public method of base class
public void readers(string name, string subject)
{
this.name = name;
this.subject = subject;
Console.WriteLine("Myself: " + name);
Console.WriteLine("My Favorite Subject is: " + subject);
}
}
class IT : STD
{
// constructor of derived class
public IT()
{
Console.WriteLine("IT students");
}
}
class PROGRAM
{
// Main Method
static void Main(string[] args)
{
// creating object of derived class
IT i = new IT();
// calling the method of base class
// using the derived class object
i.readers("XYZ", "C#");
Console.ReadKey();
}
}
}
15. C# Constructor
In C#, constructor is a special method which is
invoked automatically at the time of object
creation. It is used to initialize the data members
of new object generally. The constructor in C#
has the same name as class or struct.
There can be two types of constructors in C#.
• Default constructor
• Parameterized constructor
16. C# Default Constructor
A constructor which has no argument is known
as default constructor. It is invoked at the time
of creating object.
C# Parameterized Constructor
A constructor which has parameters is called
parameterized constructor. It is used to provide
different values to distinct objects.
17. //Program for constructor overloading
using System;
public class Employee
{
public int id;
public String name;
public float salary;
public Employee(int i, String n, float s)
{
id = i;
name = n;
salary = s;
}
public void display()
{
Console.WriteLine(id + " " + name + " " + salary);
}
public Employee()
{
Console.WriteLine("Default Constructor Invoked");
}
}
class TestEmployee
{
public static void Main(string[] args)
{
Employee e1 = new Employee(101, "xyz", 890000f);
Employee e2 = new Employee(102, "Mhh", 490000f);
Employee e3 = new Employee();
e1.display();
e2.display();
e3.display();
}
}
18. C# Destructor
A destructor works opposite to constructor, It destructs
the objects of classes. It can be defined only once in a
class. Like constructors, it is invoked automatically.
Note: C# destructor cannot have parameters. Moreover,
modifiers can't be applied on destructors.
• ~Employee()
• {
• Console.WriteLine("Destructor Invoked");
• }
19. this
in C#
In c# programming, this is a keyword that refers to
the current instance of the class. There can be 3
main usage of this keyword in C#.
• It can be used to refer current class instance
variable. It is used if field names (instance
variables) and parameter names are same, that is
why both can be distinguish easily.
• It can be used to pass current object as a
parameter to another method.
• It can be used to declare indexers.
20. using System;
public class Employee
{
public int id;
public String name;
public float salary;
public Employee(int id, String name,float salary)
{
this.id = id;
this.name = name;
this.salary = salary;
}
public void display()
{
Console.WriteLine(id + " " + name+" "+salary);
}
}
class TestEmployee{
public static void Main(string[] args)
{
Employee e1 = new Employee(101, "Sss", 890000f);
Employee e2 = new Employee(102, "Mmm", 490000f);
e1.display();
e2.display();
}
}
21. C# static
When a member is declared static, it can be accessed
with the name of its class directly.
Static is a modifier in C# which is applicable for the
following:
• Classes
• Variables
• Methods
• Constructor
It is also applicable to properties, event, and operators.
22. Program count number of object
• using System;
• public class Account
• {
• public int accno;
• public String name;
• public static int count=0;
• public Account(int accno, String name)
• {
• this.accno = accno;
• this.name = name;
• count++;
• }
•
• public void display()
• {
• Console.WriteLine(accno + " " + name);
• }
• }
• class TestAccount{
• public static void Main(string[] args)
•
• Account a1 = new Account(101, "Ssss");
• Account a2 = new Account(102, "Mmm”);
• Account a3 = new Account(103, "Aaaa”);
• a1.display();
• a2.display();
• a3.display();
• Console.WriteLine("Total Objects are: "+Account.count);
• }
• }
23. Sealed Class
Sealed classes are used to restrict the inheritance
feature of object oriented programming. Once a class is
defined as a sealed class, this class cannot be inherited.
In C#, the sealed modifier is used to declare a class
as sealed
• // Sealed class
• sealed class SealedClass
• {
• }
24. C# static class
The C# static class is like the normal class but it
cannot be instantiated. It can have only static
members
• C# static class contains only static members.
• C# static class cannot be instantiated.
• C# static class is sealed.
• C# static class cannot contain instance
constructors.
25. //Static class
• 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));
• }
• }
26. C# static constructor
C# static constructor is used to initialize static
fields. It can also be used to perform any action
that is to be performed only once. It is invoked
automatically before first instance is created or
any static member is referenced.
• C# static constructor cannot have any modifier
or parameter.
• C# static constructor is invoked implicitly. It
can't be called explicitly.
27. //static constructor
• using System;
• public class Account
• {
• public int id;
• public String name;
• public static float rateOfInterest;
• public Account(int id, String name)
• {
• this.id = id;
• this.name = name;
• }
• static Account()
• {
• rateOfInterest = 9.5f;
• }
• public void display()
• {
• Console.WriteLine(id + " " + name+" "+rateOfInterest);
• }
• }
• class TestEmployee{
• public static void Main(string[] args)
• {
• Account a1 = new Account(101, "Sonoo");
• Account a2 = new Account(102, "Mahesh");
• a1.display();
• a2.display();
•
• }
• }
28. Properties
A property is like a combination of a variable and a
method, and it has two methods: a get and a set
method
The meaning of Encapsulation, is to make sure that
"sensitive" data is hidden from users. To achieve
this, you must:
• declare fields/variables as private
• provide public get and set methods, through
properties, to access and update the value of a
private field
29. • 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 = “C# is bestl";
• Console.WriteLine("Employee Name: " + e1.Name);
•
• }
• }
30. 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:
• Abstract class
• Interface
Abstract class and interface both can have
abstract methods which are necessary for
abstraction.
31. Abstract classes
Abstract classes, marked by the
keyword abstract in the class definition, are
typically used to define a base class in the
hierarchy. What's special about them, is that
you can't create an instance of them - if you try,
you will get a compile error. Instead, you have to
subclass them, and create an instance of your
subclass. It can have abstract and non-abstract
methods.
32. 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.
33. 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();
}
}
34. 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.
35. • Interfaces specify what a class must do and not how.
• Interfaces can’t have private members.
• By default all the members of Interface are public and
abstract.
• The interface will always defined with the help of
keyword ‘interface‘.
• Interface cannot contain fields because they represent
a particular implementation of data.
• Multiple inheritance is possible with the help of
Interfaces but not with classes.
37. WHAT IS EXCEPTION?
Before starting to learn Exception handling, it is necessary
to know what actually Exception is and why it is
necessary to learn exception handling. Exception stands
for programming error which appears at runtime. For
example, you have made a program in which user inputs
two numbers and program divide the number and show
output. Now consider what happens if user input zeroes
as a second or first number. As we all know that any
number divided by zero returns infinite. In this condition,
your program breaks unconditionally by showing
DivideByZeroException. To handle any runtime error you
must keep your code under exception handling block.
38. Exception Handling gives a way to control
runtime programming error in a structured and
controlled manner. If any runtime error appears
the handler shows easy readable message
telling user what the problem is and continue
the program.
39. HOW TO HANDLE EXCEPTION AT
RUNTIME?
All the exception handling is based on only four keywords: try,
catch, throw and finally. All Exception class is derived
from System.Exception namespace.
• try: try keyword is used for identifying code block which
may cause exception at runtime.
• catch: catch keyword handle the exception if try block
raises exception. The code under try block if raises runtime
error, try block sends handler to catch block to handle error.
• throw: throw keyword is used for creating user defined
exception messages.
• finally: finally block executed whether exception is raised
or not. It is used for cleaning resource and executing set of
code.
40. TRY CATCH FINALLY
Try Catch Finally is the basic building block of
exception handling in c#. 'Try' block keeps the
code which may raise exception at runtime.
The 'catch' block handle the exception if try
block gets error and 'finally' block executes
always whether exception is raised or not. A try
block may have multiple catch blocks
41. using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exception_Handling
{
class Program
{
static void Main(string[] args)
{
label:
// Try block: The code which may raise exception at runtime
try
{
int num1, num2;
decimal result;
Console.WriteLine("Divide Program. You Enter 2 number and we return result");
Console.WriteLine("Enter 1st Number: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter 2nd Number: ");
num2 = Convert.ToInt32(Console.ReadLine());
result = (decimal)num1 / (decimal)num2;
Console.WriteLine("Divide : " + result.ToString());
Console.ReadLine();
}
42. //Multiple Catch block to handle exception
catch (DivideByZeroException dex)
{
Console.WriteLine("You have Entered 0");
Console.WriteLine("More Details about Error: nn" + dex.ToString() + "nn");
goto label;
}
catch (FormatException fex)
{
Console.WriteLine("Invalid Input");
Console.WriteLine("More Details about Error: nn" + fex.ToString() + "nn");
goto label;
}
//Parent Exception: Catch all type of exception
catch (Exception ex)
{
Console.WriteLine("Othe Exception raised" + ex.ToString() + "nn");
goto label;
}
//Finally block: it always executes
finally
{
Console.WriteLine(" For Exit Press Enter ");
Console.ReadLine();
}
}
}
}
43. User defined exception
using System;
namespace u1
{
class Program
{
static void Main(string[] args)
{
int acceptorder;
Console.WriteLine("Welcome to Shopping Site:nHow many books you want to buy (max 10):");
acceptorder = Convert.ToInt32(Console.ReadLine());
try
{
if (acceptorder == 10 || acceptorder < 10)
{
Console.WriteLine("Congratulations! You have bought {0} books", acceptorder);
Console.ReadLine();
}
else
{
throw (new maxlimit(" The number of item you want to buy is out of stock."));
}
}
catch (maxlimit m)
{
Console.WriteLine(m.Message.ToString());
Console.ReadLine();
}
}
}
//Creating Custome Exception - OutofStockException
public class maxlimit : Exception
{
public maxlimit (string message): base(message)
{
Console.WriteLine("hell"
}
}
}
44. WHAT IS SYSTEM EXCEPTION?
System Exception is predefined Exception class
in C# that is ready to use in programming. Just
choose which exception may occur in your code
and use it in a catch block.
45. Checked And Unchecked
// SAMPLE TO EXPLAIN CONCEPT
using System;
namespace Checked_Unchecked
{
class Program
{
static void Main(string[] args)
{
sbyte num1 = 20, num2 = 30, result;
result = (sbyte)(num1 * num2);
Console.WriteLine("{0} x {1} = {2}", num1, num2, result);
Console.ReadKey();
}
}
}
//The size of sbyte is -128 to 127 only; so the result is overflowed.
46. Checked strictly monitor your code and if any
overflow exception generated it sends control to
catch for handling exception.
Unchecked statement ignores overflow
exception and shows output.
47. EXAMPLE of checked and unchecked
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Checked_Unchecked
{
class Program
{
static void Main(string[] args)
{
sbyte num1 = 20, num2 = 30, result;
try
{
unchecked
{
result = (sbyte)(num1 * num2);
Console.WriteLine("from unchecked {0} x {1} = {2}", num1, num2, result);
}
checked
{
result = (sbyte)(num1 * num2);
Console.WriteLine("from checked {0} x {1} = {2}", num1, num2, result);
}
}
catch (OverflowException oex)
{
Console.WriteLine(oex.Message);
}
Console.ReadKey();
}
}
}
48. Write a program to handle NullReferenceException and fix the error message "Object reference not set to an instance of an object."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Null_Reference_Exception
{
class Program
{
static void Main(string[] args)
{
string text = null;
try
{
int length = text.Length;
Console.WriteLine(length);
Console.ReadLine();
}
catch (NullReferenceException nex)
{
Console.WriteLine(nex.Message);
}
Console.ReadLine();
}
}
}
49. Encapsulation And Abstraction
Encapsulation and abstraction is the advanced
mechanism in C# that lets your program to hide
unwanted code within a capsule and shows only
essential features of an object. Encapsulation is
used to hide its members from outside class or
interface, whereas abstraction is used to show
only essential features.
50. What is Access Specifiers in C#?
Access Specifiers defines the scope of a class
member. A class member can be variable or
function. In C# there are five types of access
specifiers are available.
List of Access Specifiers
• Public Access Specifiers
• Private Access Specifiers
• Protected Access Specifiers
• Internal Access Specifiers
• Protected Internal Access Specifiers.
51. • Public Access Specifiers
The class member, that is defined as a public can be accessed by other class members that are initialized outside the class. A
public member can be accessed from anywhere even outside the namespace
Private Access Specifiers (C#)
The private access specifiers restrict the member variable or function to be called outside of the parent class. A private function or
variable cannot be called outside of the same class. It hides its member variable and method from other class and methods
Protected Access Specifiers
The protected access specifier hides its member variables and functions from other classes and objects. This type of variable or
function can only be accessed in child class. It becomes very important while implementing inheritance.
C# Internal Access Specifiers
The internal access specifier hides its member variables and methods from other classes and objects, that is resides in other
namespace. The variable or classes that are declared with internal can be access by any member within application
C# Protected Internal Access Specifiers
The protected internal access specifier allows its members to be accessed in derived class, containing class or classes within same
application. However, this access specifier rarely used in C# programming but it becomes important while implementing
inheritance.
52. Get Set Modifier
• Properties are an extension of fields and are accessed
using the same syntax. They use accessors through
which the values of the private fields can be read,
written or manipulated.
• The get set accessor or modifier mostly used for
storing and retrieving the value from the private field.
• In simple word, the get method used for retrieving the
value from private field whereas set method used for
storing the value in private variables.
53. namespace Get_Set
{
class access
{
// String Variable declared as private
private static string name;
public void print()
{
Console.WriteLine("nMy name is " + name);
}
public string Name //Creating Name property
{
get //get method for returning value
{
return name;
}
set // set method for storing value in name field.
{
name = value;
}
}
}
class Program
{
static void Main(string[] args)
{
access ac = new access();
Console.Write("Enter your name:t");
// Accepting value via Name property
ac.Name = Console.ReadLine();
ac.print();
Console.ReadLine();
}
}
}
•
54. Classes And Methods In C#
• A class in C# is a blueprint or template that is
used for declaring an object. However, there is no
need to declare an object of the static class. A
class consists of member variables, functions,
properties etc. A method is a block of code in C#
programming. The function makes program
modular and easy to understand.
• In object oriented programming, classes and
methods are the essential thing. It provides
reusability of code and makes c# programming
more secure.
55. Example of class
namespace Creating_Class
{
class accept //Creating 1st. class
{
public string name;
public void acceptdetails()
{
Console.Write("Enter your name:t");
name = Console.ReadLine();
}
}
class print // Creating 2nd class
{
public void printdetails()
{
//Creating object of 1st. class
accept a = new accept();
//executing method of 1st class.
a.acceptdetails();
//Printing value of name variable
Console.WriteLine("e;Your name is "e; + a.name);
}
}
class Program //Creating 3rd class
{
static void Main(string[] args)
{
print p = new print();
p.printdetails();
Console.ReadLine();
}
}
}
56. Static Method And Variables
Whenever you write a function or declare a variable, it doesn’t create an instance in a memory until you create an object of the class. But if you declare any
function or variable with a static modifier, it directly creates an instance in a memory and acts globally. The static modifier doesn't reference any object.
//Power of a number using static
using System;
namespace Static_var_and_fun
{
class number
{
// Create static variable
public static int num;
//Create static method
public static void power()
{
Console.WriteLine("Power of {0} = {1}", num, num * num);
Console.ReadLine();
}
}
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a numbert");
number.num = Convert.ToInt32(Console.ReadLine());
number.power();
}
}
}
57. WHY THE MAIN METHOD IS ALWAYS DECLARED WITH STATIC?
The Main method in C# is always declared with static because it
can’t be called in another method of function.
The Main method instantiates other objects and variables but
there is no any method there that can instantiate the main
method in C#.
On another hand, the main method doesn’t accept parameter
from any other function. It only takes a parameter as an
argument via command line argument.
58. Command Line Argument
• Parameter(s) can be passed to a Main() method in C# and it is called command line
argument.
• Main() method is where program stars execution. The main method doesn’t accept
parameter from any method. It accepts parameter through the command line. It is an array
type parameter that can accept n number of parameters at runtime.
STEPS
1. Open Notepad and write the following code and save it with anyname.cs
2. Open visual studio command prompt and compile the code as follow:
Set current path, where your program is saved.
Compile it with csc anyname.cs
3. Now execute the program using following command line argument:
anyname a1 a2
59. Inheritance
using System;
namespace Basic_Example
{
//Creating Base Class
class Tyre
{
protected void TyreType()
{
Console.WriteLine("This is Tubeless Tyre");
}
}
//Creating Child Class
class Scooter : Tyre
{
public void ScooterType()
{
Console.WriteLine("Scooter Color is Red");
TyreType();
}
}
//Creating Child Class
class Car : Tyre
{
public void CarType()
{
Console.WriteLine("Car Type : Ferrari");
TyreType();
}
}
class Program
{
static void Main(string[] args)
{
Scooter sc = new Scooter();
sc.ScooterType();
Car c = new Car();
c.CarType();
Console.ReadKey();
60. Inheritance And Constructors
//SEE NEXT PAGE
If base class has constructor then child class or derived class are
required to call the constructor from its base class.
class childclass : baseclass
{
public childclass()
{
}
public childclass(string message) : base(message)
{ }
}
61. In C#, both the base class and the derived class can
have their own constructor.
In inheritance, the derived class inherits all the
members(fields, methods) of the base class,
but derived class cannot inherit the constructor of
the base class because constructors are not the
members of the class.
Instead of inheriting constructors by the derived
class, it is only allowed to invoke the constructor of
base class.
62. Simple program for base class constructor
using System;
namespace Inheritance_Constructors
{
class baseclass
{
public baseclass()
{
Console.WriteLine("I am Default Constructors");
}
public baseclass(string message)
{
Console.WriteLine("Constructor Message : " + message);
}
}
class childclass : baseclass
{
public childclass(string message) : base(message)
{
}
}
class Program
{
static void Main(string[] args)
{
//childclass ch = new childclass();
childclass ch1 = new childclass("Hello Parent");
Console.ReadKey();
}
}
}