C# - Ii Unit
C# - Ii Unit
Example:
interface Animal
{
void animalSound(); // interface method (does not have a body)
void run(); // interface method (does not have a body)
}
Two types:
• Default constructor
• Parameterized constructor
Example:
using System;
public class Employee
{
public Employee() //constructor
{
Console.WriteLine("Default Constructor Invoked");
}
public static void Main(string[] args)
{
Employee e1 = new Employee();
Employee e2 = new Employee();
}
}
Output:
Default Constructor Invoked
Default Constructor Invoked
Example:
using System;
class Geek {
// data members of the class.
String name;
int id;
Geek(String name, int id) //ParameterizedConstructor
{
this.name = name;
this.id = id;
}
public static void Main() // Main Method
{
Geek geek1=new Geek("GFG",1); //invoking parameterized constructor
Console.WriteLine("GeekName = " + geek1.name +
" and GeekId = " + geek1.id);
}
}
Output:
GeekName = GFG and GeekId = 1
Example:
using System;
class Car {
When one class inherits another class which is further inherited by another class, it is
known as Multi-level Inheritance. For example, three classes called A, B, and C, as shown
in the below image, where class C is derived from class B and class B, is derived from class
A. In this situation, each derived class inherit all the characteristics of its base classes. So
class C inherits all the features of class A and B
Syntax:
class A
{
…..
}
Class B : A //first level derivation
{
…..
}
Class C : B //second level derivation
{
…..
}
Example:
using System;
public class Animal
{
public void eat() { Console.WriteLine("Eating..."); }
}
public class Dog: Animal //first level derivation
{
public void bark() { Console.WriteLine("Barking..."); }
}
public class BabyDog : Dog //second level derivation
{
public void weep() { Console.WriteLine("Weeping..."); }
}
class TestInheritance2
{
public static void Main(string[] args)
{
BabyDog d1 = new BabyDog();
d1.eat();
d1.bark();
d1.weep();
}
}
Output:
Eating...
Barking...
Weeping...
So for instance, if you have two classes: Class1 and Class2, private members from Class1 can
only be used within Class1. You can't create a new instance of Class1 inside of Class2, and
then expect to be able to use its private members.
If Class2 inherits from Class1, then only non-private members can be reached from inside of
Class2.
7. What is Interface? Explain the defining , extending and implementing 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. Any class that implements the interface will provide an implementation
of the members defined in the interface.
Defining Interfaces
Interfaces define properties, methods and events, which are the members of the interface.
Interfaces contain only the declaration of the members. It is the responsibility of the deriving
class to define the members.
Syntax:
interface InterfaceName
{
Member declarations;
}
Extending an Interface
Like classes, interfaces can also be extended. An interface can be sub interfaced from
other interfaces. The new sub interface will inherit all the members of the super interface.
Syntax:
interface name2 : name1
{
Members of name2
}
Implementing an Interface
Interfaces are used as super classes whose properties are inherited by classes. It is
therefore necessary to create a class that inherits the given interface.
Syntax:
class classname : interface name
{
Body of classname
}
Example:
using System;
interface IPolygon
{
void calculateArea(int l, int b); // method without body
}
class Rectangle : IPolygon
{
public void calculateArea(int l, int b) // implementation of methods
{
int area = l * b;
Console.WriteLine("Area of Rectangle: " + area);
}
}
class Program{
static void Main(string[] args){
The general forms of operator overloading in the case of unary operator follows the syntax
given below.
Here, the return type can be anything, but it should not be void for the operators like +,-,
~ and .(dot). The return type of this operator should be either an integer or a Boolean type. It
is important to note that the Boolean operators roll out true and false and hence can be
overloaded only as pairs. A compilation error would occur if not done because a class generally
declares this operator without declaring the other.
The general forms of operator overloading in the case of unary operator follows the syntax
given below.
Here, the return type can be anything, but it should not be void for the operators like +,-,
~ and .(dot). The return type of this operator should be either an integer or a Boolean type. It
is important to note that the Boolean operators roll out true and false and hence can be
overloaded only as pairs. A compilation error would occur if not done because a class generally
declares this operator without declaring the other.
Example:
using System;
namespace Calculator {
class Calculator {
public int number1 , number2;
public Calculator(int num1 , int num2)
{
number1 = num1;
number2 = num2;
}
class EntryPoint{
static void Main(String []args) {
Output:
Number1 = -15
Number2 = 25
Example:
using System;
namespace BinaryOverload {
class Calculator {
public int number = 0;
public Calculator() {} // no-argument constructor
public Calculator(int n) // parameterized constructor
{
number = n;
}
// Overloading of Binary "+" operator
public static Calculator operator + (Calculator Calc1,Calculator Calc2)
{
Calculator Calc3 = new Calculator(0);
Calc3.number = Calc2.number + Calc1.number;
return Calc3;
}
public void display() // function to display result
{
Console.WriteLine("{0}", number);
}
}
class CalNum {
static void Main(string[] args) {
11. Explain with syntax and example, how delegates are declared.
Delegate type can be declared using the delegate keyword. Once a delegate is declared,
delegate instance will refer and call those methods whose return type and parameter-list
matches with the delegate declaration.
Syntax:
modifier delegate return-type delegate-name (parameter list);
• The delegate key word represents that the declaration represents a class type derived
from System.Delegate.
• The return type indicates the return type of the delegate.
• Parameter list contains the parameters which are required by the method when called
through the delegate. Parameters identify the signature of the delegate.
• The delegate-name is any valid C# identifier and represents the name of the delegate that
will be used to instantiate the delegate objects.
• The modifier controls the accessibility of the delegate. Delegates can take the following
modifiers i.e. new, public, private, protected and internal.
A delegate may be defined in the following places:
✓ Inside a class
✓ Outside a class
✓ As a top level object in a namespace
Example:
public delegate int GeeksForGeeks (int G, int F, int G);
The parameters passed to the delegate by the caller are passed to the method, and the return
value, if any, from the method, is returned to the caller by the delegate. This is known as
invoking the delegate.
Syntax:
delegate_object (parameters list)
Example:
using System;
delegate int Calculator(int n); //declaring delegate
Console.ReadKey();
}
}
14. With syntax and example explain exception handling mechanism in C#.
C# exception handling is built upon four keywords:
• try − This block holds the code that may throw an exception. It is followed by one or
more catch blocks.
• catch − This block catches the exception thrown by the try block. The catch keyword
indicates the catching of an exception.
• finally − The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed
whether an exception is raised or not.
• throw − A program throws an exception when a problem shows up. This is done
using a throw keyword.
Syntax:
try {
// statements causing exception
}
catch ( ExceptionName e1 ) {
// error handling code
}
catch ( ExceptionName e2 ) {
// error handling code
}
finally {
// statements to be executed
}
Example:
class Program{
static void Main(string[] args)
{
try
{
int num = 0;
int result = 100 / num; //exception occurs
Console.WriteLine( result);
}
catch (DivideByZeroException e)
{
Console.WriteLine(e); //exception caught by catch block
}