0% found this document useful (0 votes)
0 views22 pages

Unit4 Csharp

This document covers object-oriented concepts in C#, focusing on inheritance, including single-level, multi-level, sealed classes, abstract classes, and interfaces. It provides examples and explanations of how these concepts work, including code snippets demonstrating inheritance and method overriding. Additionally, it discusses namespaces and name hiding in C#, highlighting the use of the 'new' keyword to prevent warnings when hiding base class members.

Uploaded by

Rajeevkumar S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views22 pages

Unit4 Csharp

This document covers object-oriented concepts in C#, focusing on inheritance, including single-level, multi-level, sealed classes, abstract classes, and interfaces. It provides examples and explanations of how these concepts work, including code snippets demonstrating inheritance and method overriding. Additionally, it discusses namespaces and name hiding in C#, highlighting the use of the 'new' keyword to prevent warnings when hiding base class members.

Uploaded by

Rajeevkumar S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

C # PROG.

[ UCS15601] Unit-4 DrRajeev Sharma

UNIT IV - OBJECT-ORIENTED CONCEPTS IN C#


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.

C# Single Level Inheritance Example: Inheriting Fields

When one class inherits another class, it is known as single level inheritance. Let's see
the example of single level inheritance which inherits the fields only.

1. using System;
2. public class Employee
3. {
4. public float salary = 40000;
5. }
6. public class Programmer: Employee
7. {
8. public float bonus = 10000;
9. }
10. class TestInheritance{
11. public static void Main(string[] args)
12. {
13. Programmer p1 = new Programmer();
14.
15. Console.WriteLine("Salary: " + p1.salary);
16. Console.WriteLine("Bonus: " + p1.bonus);
17.
18. }
19. }

Output:

Unit-4 Page 1
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

Salary: 40000
Bonus: 10000

In the above example, Employee is the base class and Programmer is

the derived class.

C# Single Level Inheritance Example: Inheriting Methods

Let's see another example of inheritance in C# which inherits methods only.

1. using System;
2. public class Animal
3. {
4. public void eat() { Console.WriteLine("Eating..."); }
5. }
6. public class Dog: Animal
7. {
8. public void bark() { Console.WriteLine("Barking..."); }
9. }
10. class TestInheritance2{
11. public static void Main(string[] args)
12. {
13. Dog d1 = new Dog();
14. d1.eat();
15. d1.bark();
16. }
17. }

Output:

Eating...
Barking...

C# Multi Level Inheritance Example

When one class inherits another class which is further inherited by another class, it is
known as multi level inheritance in C#. Inheritance is transitive so the last derived class
acquires all the members of all its base classes.
Let's see the example of multi level inheritance in C#.

Unit-4 Page 2
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

1. using System;
2. public class Animal
3. {
4. public void eat() { Console.WriteLine("Eating..."); }
5. }
6. public class Dog: Animal
7. {
8. public void bark() { Console.WriteLine("Barking..."); }
9. }
10. public class BabyDog : Dog
11. {
12. public void weep() { Console.WriteLine("Weeping..."); }
13. }
14. class TestInheritance2{
15. public static void Main(string[] args)
16. {
17. BabyDog d1 = new BabyDog();
18. d1.eat();
19. d1.bark();
20. d1.weep();
21. }
22. }

Output:

Eating...
Barking...
Weeping...

Note: Multiple inheritance is not supported in C# through class.

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.

Unit-4 Page 3
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

Note: Structs are implicitly sealed therefore they can't be inherited.

C# Sealed class
C# sealed class cannot be derived by any class. Let's see an example of sealed class in
C#.

1. using System;
2. sealed public class Animal{
3. public void eat() { Console.WriteLine("eating..."); }
4. }
5. public class Dog: Animal
6. {
7. public void bark() { Console.WriteLine("barking..."); }
8. }
9. public class TestSealed
10. {
11. public static void Main()
12. {
13. Dog d = new Dog();
14. d.eat();
15. d.bark();
16. }
17. }

Output:

Compile Time Error: 'Dog': cannot derive from sealed type 'Animal'

C# Sealed method
The sealed method in C# cannot be overridden further. It must be used with override
keyword in method.

Let's see an example of sealed method in C#.

1. using System;
2. public class Animal{
3. public virtual void eat() { Console.WriteLine("eating..."); }
4. public virtual void run() { Console.WriteLine("running..."); }

Unit-4 Page 4
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

5.
6. }
7. public class Dog: Animal
8. {
9. public override void eat() { Console.WriteLine("eating bread..."); }
10. public sealed override void run() {
11. Console.WriteLine("running very fast...");
12. }
13. }
14. public class BabyDog : Dog
15. {
16. public override void eat() { Console.WriteLine("eating biscuits..."); }
17. public override void run() { Console.WriteLine("running slowly..."); }
18. }
19. public class TestSealed
20. {
21. public static void Main()
22. {
23. BabyDog d = new BabyDog();
24. d.eat();
25. d.run();
26. }
27. }

Output:

Compile Time Error: 'BabyDog.run()': cannot override inherited member


'Dog.run()' because it is sealed

Note: Local variables can't be sealed.

1. using System;
2. public class TestSealed
3. {
4. public static void Main()
5. {
6. sealed int x = 10;
7. x++;
8. Console.WriteLine(x);
Unit-4 Page 5
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

9. }
10. }

Output:

Compile Time Error: Invalid expression term 'sealed'

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

An abstract method in C# is internally a virtual method so it can be overridden by the


derived class.

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.

Unit-4 Page 6
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

Let's see an 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.

1. using System;
2. public abstract class Shape
3. {
4. public abstract void draw();
5. }
6. public class Rectangle : Shape
7. {
8. public override void draw()
9. {
10. Console.WriteLine("drawing rectangle...");
11. }
12. }
13. public class Circle : Shape
14. {
15. public override void draw()
16. {
17. Console.WriteLine("drawing circle...");
18. }
19. }
20. public class TestAbstract
21. {
22. public static void Main()
23. {
24. Shape s;
25. s = new Rectangle();
26. s.draw();
27. s = new Circle();
28. s.draw();
29. }
30. }

Output:

drawing ractangle...
drawing circle...

Unit-4 Page 7
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

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
Let's see the example of interface in C# which has draw() method. Its implementation is
provided by two classes: Rectangle and Circle.
1. using System;
2. public interface Drawable
3. {
4. void draw();
5. }
6. public class Rectangle : Drawable
7. {
8. public void draw()
9. {

10. Console.WriteLine("drawing rectangle...");


11. }
12. }
13. public class Circle : Drawable
14. {
15. public void draw()
16. {

17. Console.WriteLine("drawing circle...");


18. }
19. }
20. public class TestInterface
21. {
22. public static void Main()
23. {

Unit-4 Page 8
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

24. Drawable d;
25. d = new Rectangle();
26. d.draw();
27. d = new Circle();
28. d.draw();
29. }
30. }
Output:
drawing ractangle...
drawing circle...

Note: Interface methods are public and abstract by default. You cannot explicitly use
public and abstract keywords for an interface method.

1. using System;
2. public interface Drawable
3. {
4. public abstract void draw();//Compile Time Error
5. }

C# Namespaces
Namespaces in C# are used to organize too many classes so that it can be easy to
handle the application.
In a simple C# program, we use System.Console where System is the namespace and
Console is the class. To access the class of a namespace, we need to use
namespacename.classname. We can use using keyword so that we don't have to use
complete name all the time.
In C#, global namespace is the root namespace. The global::System will always refer to
the namespace "System" of .Net Framework.

C# namespace example
Let's see a simple example of namespace which contains one class "Program".
1. using System;
2. namespace ConsoleApplication1
3. {
4. class Program
5. {
6. static void Main(string[] args)

Unit-4 Page 9
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

7. {

8. Console.WriteLine("Hello Namespace!");
9. }
10. }
11. }
Output:
Hello Namespace!

C# namespace example: by fully qualified name


Let's see another example of namespace in C# where one namespace program accesses
another namespace program.
1. using System;
2. namespace First {
3. public class Hello
4. {

5. public void sayHello() { Console.WriteLine("Hello First Namespace"); }


6. }
7. }
8. namespace Second
9. {
10. public class Hello
11. {

12. public void sayHello() { Console.WriteLine("Hello Second Namespace"); }


13. }
14. }
15. public class TestNamespace
16. {
17. public static void Main()
18. {
19. First.Hello h1 = new First.Hello();
20. Second.Hello h2 = new Second.Hello();
21. h1.sayHello();
22. h2.sayHello();
23.
24. }
25. } Output:
Hello First Namespace
Hello Second Namespace

Unit-4 Page 10
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

C# namespace example: by using keyword


Let's see another example of namespace where we are using "using" keyword so that we
don't have to use complete name for accessing a namespace program.
1. using System;
2. using First;
3. using Second;
4. namespace First {
5. public class Hello
6. {

7. public void sayHello() { Console.WriteLine("Hello Namespace"); }


8. }
9. }
10. namespace Second
11. {
12. public class Welcome
13. {

14. public void sayWelcome() { Console.WriteLine("Welcome Namespace"); }


15. }
16. }
17. public class TestNamespace
18. {
19. public static void Main()
20. {
21. Hello h1 = new Hello();
22. Welcome w1 = new Welcome();
23. h1.sayHello();
24. w1.sayWelcome();
25. }
26. }
Output:
Hello Namespace
Welcome Namespace

Unit-4 Page 11
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

Inheritance and Name Hiding


It is possible for a derived class to define a member that has the same name as a member in its base
class. When this happens, the member in the base class is hidden within the derived class. While this
is not technically an error in C#, the compiler will issue a warning message. This warning alerts you to
the fact that a name is being hidden. If your intent is to hide a base class member, then to prevent
this warning, the derived class member must be preceded by the new keyword. Understand that this
use of new is separate and distinct from its use when creating an object instance.

The output produced by this program is shown here: i in derived class: 2


Since B defines its own instance variable called i, it hides the i in A. Therefore, when Show( ) is
invoked on an object of type B, the value of i as defined by B is displayed—not the one defined in A.

Using base to Access a Hidden Name


There is a second form of base that acts somewhat like this, except that it always refers to the base
class of the derived class in which it is used. This usage has the following general form:
base.member
Here, member can be either a method or an instance variable. This form of base is most applicable to
situations in which member names of a derived class hide members by the same name in the base
class. Consider this version of the class hierarchy from the preceding example:

Unit-4 Page 12
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

// Using base to overcome name hiding. using System;

Creating a Multilevel Hierarchy

C# | Multilevel Inheritance
In the Multilevel inheritance, a derived class will inherit a base class and as well as
the derived class also act as the base class to other class. 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.

Unit-4 Page 13
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

Example: Here, the derived class Rectangle is used as a base class to create the
derived class called ColorRectangle. Due to inheritance the ColorRectangle inherit
all the characteristics of Rectangle and Shape and add an extra field called rcolor,
which contains the color of the rectangle.

This example also covers the concept of constructors in a derived class. As we know
that a subclass inherits all the members (fields, methods) from its superclass but
constructors are not members, so they are not inherited by subclasses, but the
constructor of the superclass can be invoked from the subclass. As shown in the
below example, base refers to a constructor in the closest base class. The base in
ColorRectangle calls the constructor in Rectangle and the base in Rectangle class
the constructor in Shape.
// C# program to illustrate the
// concept of multilevel inheritance
using System;

class Shape {

double a_width;
double a_length;

// Default constructor
public Shape()
{
Width = Length = 0.0;
}

// Constructor for Shape


public Shape(double w, double l)
{
Width = w;
Length = l;
}

// Construct an object with


// equal length and width
public Shape(double y)
{
Width = Length = y;
}

// Properties for Length and Width


public double Width
{
get {
return a_width;
}

set {

Unit-4 Page 14
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

a_width = value < 0 ? -value : value;


}
}

public double Length


{
get {
return a_length;
}

set {
a_length = value < 0 ? -value : value;
}
}
public void DisplayDim()
{
Console.WriteLine("Width and Length are "
+ Width + " and " + Length);
}
}

// A derived class of Shape


// for the rectangle.
class Rectangle : Shape {

string Style;

// A default constructor.
// This invokes the default
// constructor of Shape.
public Rectangle()
{
Style = "null";
}

// Constructor
public Rectangle(string s, double w, double l)
: base(w, l)
{
Style = s;
}

// Construct an square.
public Rectangle(double y)
: base(y)
{
Style = "square";
}

// Return area of rectangle.


public double Area()
{
return Width * Length;
}

// Display a rectangle's style.


public void DisplayStyle()
{
Console.WriteLine("Rectangle is " + Style);

Unit-4 Page 15
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

}
}

// Inheriting Rectangle class


class ColorRectangle : Rectangle {

string rcolor;

// Constructor
public ColorRectangle(string c, string s,
double w, double l)
: base(s, w, l)
{
rcolor = c;
}

// Display the color.


public void DisplayColor()
{
Console.WriteLine("Color is " + rcolor);
}
}

// Driver Class
class GFG {

// Main Method
static void Main()
{
ColorRectangle r1 = new ColorRectangle("pink",
"Fibonacci rectangle", 2.0, 3.236);

ColorRectangle r2 = new ColorRectangle("black",


"Square", 4.0, 4.0);

Console.WriteLine("Details of r1: ");


r1.DisplayStyle();
r1.DisplayDim();
r1.DisplayColor();

Console.WriteLine("Area is " + r1.Area());


Console.WriteLine();

Console.WriteLine("Details of r2: ");


r2.DisplayStyle();
r2.DisplayDim();
r2.DisplayColor();

Console.WriteLine("Area is " + r2.Area());


}
}
Output:
Details of r1:
Rectangle is Fibonacci rectangle
Width and Length are 2 and 3.236
Color is pink
Unit-4 Page 16
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

Area is 6.472
Details of r2:
Rectangle is Square
Width and Length are 4 and 4
Color is black
Area is 16

The object Class


C# defines one special class called object that is an implicit base class of all other classes
and for all other types (including the value types). In other words, all other types are derived
from object. This means that a reference variable of type object can refer to an object of any
other type. Also, since arrays are implemented as objects, a variable of type object can also
refer to any array. Technically, the C# name object is just another name for System.Object,
which is part of the .NET Framework class library.
The object class defines the methods shown in Table 11-1, which means that they are
available in every object. A few of these methods warrant some additional explanation. By
default, the Equals(object) method determines if the invoking object refers to the same
object as the one referred to by the argument. (That is, it determines if the two references
are the same.) It returns true if the objects are the same, and false otherwise. You can
override this method in classes that you create. Doing so allows you to define what equality
means relative to a class.
For example, you could define Equals(object) so that it compares the contents of two
objects for equality. The Equals(object, object) method invokes Equals(object) to compute its
result. The GetHashCode( ) method returns a hash code associated with the invoking object.
This hash code can be used with any algorithm that employs hashing as a means of
accessing stored objects., if you overload the = = operator, then you will usually need to
override Equals(object) and GetHashCode( ) because most of the time you will want the = =
operator and the Equals(object) methods to function the same. When Equals( ) is
overridden, you should also override GetHashCode( ), so that the two methods are
compatible.
The ToString( ) method returns a string that contains a description of the object on which it is
called. Also, this method is automatically called when an object is output using

Unit-4 Page 17
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

WriteLine( ). Many classes override this method. Doing so allows them to tailor a description
specifically for the types of objects that they create. For example: // Demonstrate ToString()

Unit-4 Page 18
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

Unit-4 Page 19
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

Here, the value of x is automatically boxed when it is passed to Sqr( ). Boxing and unboxing
allow C#’s type system to be fully unified. All types derive from object. A reference to any
type can be assigned to a variable of type object. Boxing and unboxing automatically handle
the details for the value types. Furthermore, because all types are derived from object, they
all have access to object’s methods. For example, consider the following rather surprising
program:

Unit-4 Page 20
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

Unit-4 Page 21
C # PROG.[ UCS15601] Unit-4 DrRajeev Sharma

Unit-4 Page 22

You might also like