0% found this document useful (0 votes)
89 views20 pages

C# Unit III Notes

The document discusses the differences between classes and structures in C# and provides details about constructors. It covers default, parameterized, copy, static, and private constructors as well as constructor overloading.

Uploaded by

vishalj1006
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)
89 views20 pages

C# Unit III Notes

The document discusses the differences between classes and structures in C# and provides details about constructors. It covers default, parameterized, copy, static, and private constructors as well as constructor overloading.

Uploaded by

vishalj1006
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/ 20

Unit –III

Structure and Enumerations


Difference between Class and Structure in c# ( V. Imp)
1. Keyword for structure declaration is struct. Structure is a collection of different data type
elements sharing a common name. Structures are value types and the classes are reference
types. Before proceeding to the next point, let explain the difference between the two types.
Imagine this is the memory within the machine,

2. Classes are usually used for large amounts of data, whereas structs are usually used for smaller
amounts of data.
3. Classes can be inherited whereas structures not.
4. A structure couldn't be null like a class.
5. A structure couldn't have a destructor such as a class.
6. A structure can't be abstract, a class can.
7. You cannot override any methods within a structure except the following belonging to the type
object:

a. Equals()
b. GetHashCode()
c. GetType()
d. ToString()

And the other polymorphism technique used for structures is implementing interfaces.

8. Declared events within a class are automatically locked and then they are thread safe, in contrast
to the structure type where events can't be locked.
9. A structure must always have the default parameter less constructor defined as public but a class
might have one, so you can't define a private parameter-less constructor
10. A static constructor is triggered in the case of a class but not in the case of a structure.

11. The structure can't contain a volatile field whereas the class can
12. You can't use size of with classes but you can with structures
13. Fields are automatically initialized with classes to 0/false/null whereas structures are not
14. Fields can't be directly instantiated within structures but classes allow such operations
15. Structures and classes don't adopt the same approach for the System.
What is constructor? ( V. Imp)
A special method of the class whose name and method name is same is called constructor. It will
be automatically invoked when an instance of the class is created. The main use of constructors is to
initialize private fields of the class while creating an instance for the class. When you have
not created a constructor in the class, the compiler will automatically create a default constructor in
the class. The default constructor initializes all numeric fields in the class to zero and all string and
object fields to null.

Key points regarding the Constructor are:


 A class can have any number of constructors.
 A constructor doesn't have any return type, not even void.
 A static constructor can not be a parameterized constructor.
 Within a class you can create only one static constructor.

Types of Constructors : ( V. Imp)


1. Default Constructor
2. Parametrized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor

Default Constructor
A constructor which has no argument is known as default constructor; in other words this type
of constructor does not take parameters. It is invoked at the time of creating object.

The drawback of a default constructor is that every instance of the class will be initialized to the
same values and it is not possible to initialize each instance of the class to different values. The
default constructor initializes:

1. All numeric fields in the class to zero.


2. All string and object fields to null.

Parameterized Constructor
A constructor with at least one parameter is called a parameterized constructor. The advantage of a
parameterized constructor is that you can initialize each instance of the class to different values.
Copy Constructor ( v. Imp)
The constructor which creates an object by copying variables from another object is called a copy
constructor. The purpose of a copy constructor is to initialize a new instance to the values of an existing
instance.

Normally, C# does not provide a copy constructor for objects, but if you want to create a
copy constructor in your program you can create according to your requirement.

Copy Constructor in with example program c#.net :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CAConstructors
{
class employee4

{
int Empid, Eage;
string Ename, EAddress;

public employee4()
{
Console.WriteLine("Enter Employee Details:-");
this.Empid=Convert.ToInt32(Console.ReadLine());
this.Ename=Console.ReadLine();
this.EAddress=Console.ReadLine();
this.Eage=Convert.ToInt32(Console.ReadLine());
}
public employee4(employee4 obj1)
{
this.Empid=obj1.Empid;
this.Ename=obj1.Ename;
this.EAddress=obj1.EAddress;
this.Eage=obj1.Eage;
}
public void DisplayEmpData()
{

Console.WriteLine("Employee id is :-" + Empid);


Console.WriteLine("Employee Name is :-" + Ename);
Console.WriteLine("Employee Address is :-" + EAddress);
Console.WriteLine("Employee age is :-" + Eage);
}
}
class CopyConstructor
{
static void Main(string[] args)
{
employee4 obj1=new employee4();
employee4 obj2=new employee4(obj1);
obj1.DisplayEmpData();
obj2.DisplayEmpData();
Console.ReadLine();
}
}
}

Output:-

Without using copy constructor we can also the data of existing objects in to newly created object by
writing a statement like

Empoyee4 obj2=obj1;

when we use this statement by default all data fields data of obj1 will be copied into obj2.

But if we want to restrict copying of some data fields data it is not possible for this purpose
copy constrictor is suitable.

Realtime:-

Copy Constructor is used in real time in following situations:-

If an object contains data which is stored by getting from database (or) from some remote place over the
network for newly created object if we want the same data it is preferable to use copy constructor instead
of using getting the data from data base (or) remote place over the network.
Static Constructor
When a constructor is created as static, it will be invoked only once for all of instances of the class
and it is invoked during the creation of the first instance of the class or the first reference to a static
member in the class. A static constructor is used to initialize static fields of the class and to write the
code that needs to be executed only once.

Some key points of a static constructor is:

1. A static constructor does not take access modifiers or have parameters.


2. A static constructor is called automatically to initialize the class before the first instance is
created or any static members are referenced.
3. A static constructor cannot be called directly.
4. The user has no control on when the static constructor is executed in the program.
5. A typical use of static constructors is when the class is using a log file and the constructor is
used to write entries to this file.

Private Constructor

When a constructor is created with a private specifier, it is not possible for other classes to derive
from this class, neither is it possible to create an instance of this class. They are usually used in
classes that contain static members only. Some key points of a private constructor are:

1. One use of a private constructor is when we have only static members.


2. It provides an implementation of a singleton class pattern
3. Once we provide a constructor that is either private or public or any, the compiler will not add
the parameter-less public constructor to the class.

C# Constructor Overloading (V.V. Imp)


Prerequisite: Constructors in C#
It is quite similar to the Method Overloading. It is the ability to redefine a Constructor in
more than one form. A user can implement constructor overloading by defining two or
more constructors in a class sharing the same name. C# can distinguish the
constructors with different signatures. i.e. the constructor must have the same name but
with different parameters list. Constructor and method both can be overloaded.

We can overload constructors in different ways as follows:


 By using different type of arguments
 By using different number of arguments
 By using different order of arguments
Example :
/* PR-14 C# program to Demonstrate the overloading of constructor when the
types of arguments are different */

using System;

class ADD {

int x, y;
double f;
string s;

// 1st constructor
public ADD(int a, double b)
{
x = a;
f = b;
}

// 2nd constructor
public ADD(int a, string b)
{
y = a;
s = b;
}

// showing 1st constructor's result


public void show()
{
Console.WriteLine("1st constructor (int + float): {0} ",
(x + f));
}

// shows 2nd constructor's result


public void show1()
{
Console.WriteLine("2nd constructor (int + string): {0}",
(s + y));
}
}

// Driver Class
class GFG {

// Main Method
static void Main()
{

// Creating instance and


// passing arguments
// It will call the first constructor
ADD g = new ADD(10, 20.2);
// calling the method
g.show();

// Creating instance and


// passing arguments
// It will call the second constructor
ADD q = new ADD(10, "Roll No. is ");

// calling the method


q.show1();
}
}

What Inheritance is ? ( V.V. V. Imp)


Acquiring (taking) the properties of one class into another class is called inheritance. Inheritance
provides reusability by allowing us to extend an existing class. Public access specifier always
used for an interface.

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.

The following are the types of inheritance in C#.

The inheritance concept is based on a base class and derived class. Let us see the definition of a
base and derived class.

 Base class - is the class from which features are to be inherited into another class.
 Derived class - it is the class in which the base class features are inherited.

Single inheritance
It is the type of inheritance in which there is one base class and one derived class.
For example,

1. public class Accountcreditinfo //base class


2. {
3. public string Credit()
4. {
5. return "balance is credited";
6. }
7. }
8. public class debitinfo : Accountcreditinfo //derived class
9. {
10. public string debit()
11. {
12. Credit(); ////derived class method
13. return "balance is debited";
14. }
15. }

In the preceding sample program Accountcreditinfo is the base class and debitinfo is the derived
class.

Hierarchical inheritance
This is the type of inheritance in which there are multiple classes derived from one base class. This
type of inheritance is used when there is a requirement of one class feature that is needed in
multiple classes.
For example,

1. class A //base class


2. {
3. public string msg()
4. {
5. return "this is A class Method";
6. }
7. }
8. class B : A
9. {
10. public string info()
11. {
12. msg();
13. return "this is B class Method";
14. }
15. class C : A
16. {
17. public string getinfo()
18. {
19. msg();
20. return "this is B class Method";
21. }
22. }
23. }

In the preceding program one base class is derived in many classes hence it is a called a
Hierarchical Inheritance.
C# Program to Illustrate Hierarchical Inheritance
This C# Program Illustrates Hierarchical Inheritance. Here Single parent and multiple child and when
more than one derived class are created from single base class is called C# Hierarchical Inheritance.
Here is source code of the C# Program to Illustrate Hierarchical Inheritance. The C# program is
successfully compiled and executed with Microsoft Visual Studio.

1. /* PR-15 C# Program to Illustrate Hierarchical Inheritance */


2. using System;
3. namespace Inheritance
4. {
5. class Program
6. { static void Main(string[] args)
7. {
8. Principal P = new Principal();
9. P.Monitor();
10. Teacher T = new Teacher();
11. T.Monitor();
12. T.Teach();
13. Student S = new Student();
14. S.Monitor();
15. S.Learn();
16. Console.ReadKey();
17. }
18.
19. class Principal
20. {
21. public void Monitor()
22. {Console.WriteLine("Monitor"); }
23. }
24. class Teacher : Principal
25. {
26. public void Teach()
27. { Console.WriteLine("Teach"); }
28. }
29. class Student : Principal
30. {
31. public void Learn()
32. { Console.WriteLine("Learn"); }
33. }
34. }
35. }
Multilevel inheritance
When one class is derived from another derived class then this type of inheritance is called
multilevel inheritance.

For example,

1. public class Person


2. {
3. public string persondet()
4. {
5. return "this is the person class";
6. }
7. }
8. public class Bird : Person
9. {
10. public string birddet()
11. {
12. persondet();
13. return "this is the birddet Class";
14. }
15. }
16. public class Animal : Bird
17. {
18. public string animaldet()
19. {
20. persondet();
21. birddet();
22. return "this is the Animal Class";
23. }
24. }

In the preceding program, each class is derived from one class that is derived from another class
hence this type of inheritance is called Multilevel Inheritance.

Multiple inheritance using Interfaces


C# does not support multiple inheritances of classes. To overcome this problem we can use
interfaces, we will see more about interfaces in my next article in detail.
For example,

1. public interface IA //ineterface 1


2. {
3. string setImgs(string a);
4. }
5. public interface IB //Interface 2
6. {
7. int getAmount(int Amt);
8. }
9. public class ICar : IA, IB //implementatin
10. {
11. public int getAmount(int Amt)
12. {
13. return 100;
14. }
15. public string setImgs(string a)
16. {
17. return "this is the car";
18. }
19. }

In the preceding program the ICar class inherits the features of the two interfaces hence this type of
inheritance is called Multiple Inheritance.

The following are some key points about inheritance:

1. C# does not support multiple inheritances of classes, the same thing can be done using
interfaces.
2. Private members are not accessed in a derived class when one class is derived from
another.
How to define subclass and subclass constructor in c#? ( V. Imp)

 Sub Class: The class that inherits the other class is known as subclass(or a derived
class, extended class, or child class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.

 When we define an appropriate constructor for the derived class that may be invoked
when a derived class object is created.
 Purpose of constructor is to provide values to the data fields of the class.
 The constructor in the Subclass (derived) class uses the base keyword to pass values that
are required by the base class constructor.
 both , the base class and (Subclass) derived class has their own constructors, so the
process is complicated because the constructors of both classes must be executed. To
overcome this situation C# provide a keyword known as a base keyword. With the help of
base keyword, the derived class can call the constructor which is defined in its base class.
 Note: Any form of the constructor defined in the base class can be called by the base
keyword, but only that constructor executes that matches the arguments.

Example of defining subclass constructors :


using System;
class Room // This is Base class
{ public int length;
public int breadth;
public Room ( int x , int y ) // base constructor
{ length = x;
Breadth = y; }
public int Area()
{ return ( ength* breadth) ; }
}
Class Bedroom : Room // Subclass or derived class
{ int height ;

public Bedroom ( int x , int y, int z ) : base (x , y) // subclass constructor


{ height = z; }

public int volume ( )


{ Return( length * breadth* height) ;
}
}
Class subclasscontructor
{ public static void Main( )
{ Bedroom room1 = new Bedroom ( 20, 12, 10) ; // invoke derived constructor
int A = room1.Area(); // superclass method
int V = room1.volume();
Console.WriteLine(“ Area of room = “ + A);
Console.WriteLine(“ Volume of room = “ + V);
}
}

 When the compiler encounters base(x, y) , it passes the values of x and y to the base class
constructor which takes two int arguments. The base class constructor is called before the
derived class constructor is executed.
 Note that the use of keyword base is not only limited to the constructor logic alone.
We may use the base in any subclass to access a public or protected member defined in a
parent class. E.g. base.length =100; int area = base.Area();

Method Overriding ( V. V. Imp)


 We know that, methods defined in a superclass are inherited by its subclass and is used by the
objects created by the subclass. Method inheritance enables us to define and use methods
repeatedly in subclasses.
 When we want an object to respond to the same method but behave differently when that method
is called. That means , we should override the method define in the superclass.
 Overriding is possible by defining a method in the subclass that has the same name, same
argument and the same return type method in the superclass.
 When that method is called, the method defined in the subclass is invoked and executed instead
of the superclass. This is known as method overriding.
 Remember that :
1. You should specify the method in base class as virtual.
2. Implement the method in subclass using the keyword override.

Keywords in Method Overriding


Virtual Keyword : It tells the compiler that this method can be
overridden by derived classes.
Override Keyword : In the subclass, it tells the compiler that this
method is overriding the same named method in the base class.
Base Keyword : In the subclass, it calls the base class method for
overriding functionality.

/* Example of method overriding */


using System;
class Super // This is Base class
{ protected int x;

public Super ( int x ) // base constructor


{ this.x = x;
}
public virtual void Display( )
{ Console.WritLine ( “Super x= “+ x); }
}
Class Sub : Super // Subclass or derived class
{ int y ;

public Sub ( int x , int y) : base (x ) // subclass constructor


{ this.y = y;
}
public override void Display ( ) // method defined again with override
{ Console.WritLine ( “Super x= “+ x);
Console.WritLine ( “Sub y= “+ y); }
}
}
Class overrideprogram
{ public static void Main( )
{ Sub s1 = new sub ( 20, 10) ; // invoke derived constructor
S1.Display( ); }
}
Output :

Super x= 20

Sub y = 10

Note that : base class method has not been called. If we want to call the base method we may use
base reference as base.Display() ;

What are member Access Modifiers in c# ? (V. Imp)


All types and type members have an accessibility level, which controls whether they can
be used from other code in your assembly or other assemblies. You can use the
following access modifiers to specify the accessibility of a type or member when you
declare it:

public
The type or member can be accessed by any other code in the same assembly or another
assembly that references it.

private
The type or member can be accessed only by code in the same class or struct.

protected
The type or member can be accessed only by code in the same class, or in a class that is derived
from that class.
internal
The type or member can be accessed by any code in the same assembly, but not from another
assembly.

protected internal The type or member can be accessed by any code in the assembly in which it
is declared, or from within a derived class in another assembly.

What is the difference between class and object ?

 In object-oriented terminology, a Class is a template for Objects and every Object must
belong to a Class.

 A class is a construct that defines a collection of properties and methods in a single unit,
which does not change during the execution of a program.

 Objects are created and eventually destroyed during the execution of a program, so they
only live in the program for a short time. While objects are "living" their attributes may
also be changed at execution of a program.

 Every object belongs to a class and every class contains one or more related objects. That
means, a Class is created once and Object is created from the same Class many time as
they require. There is no memory space allocation for a Class when it is crated, while
memory space is allocated for an Object when it is created.
Abstract Class :

In many applications, we would have one base class and numbers of different derived classes.
The top-most base class simply acts as a base for others and is not useful on its own. In such
situation, you may not want to create its objects by making the base class abstract.
The abstract is a modifier and when used to declare a class indicates that the class cannot be
instantiated, only its derived (subclass) classes can be instantiated.
Example :
Abstract class base
{ ….
……
}
Class derived : base
{ ….
……
}
base b ; // Error i.e. not Applicable
derived d ; // OK i.e. Applicable
Characteristics of abstract class :
 We cannot create objects of Base type but we can derive its subclasses objects.
 It can have abstract members.
 We can not apply a sealed modifier to it.

Abstract Methods :

When an instance method declaration includes the modifier abstract , the method is said to be an
abstract method.
Example : public abstract void draw( int x, int y) ; // no method body only semicolon

characteristics of abstract method are :

 An abstract method is implicitly a virtual method and does not provide any
implementation.
 It does not have method body. Method body simply consist of semicolon.
 It can be declared only in abstract classes.
 It cannot take either static or virtual modifiers.
 Its implementation must be provided in non abstract derived classes by overriding the
method.
 An abstract declaration is permitted to override a virtual method.

Sealed class :
A class that cannot be subclassed is called a sealed class. It is used to prevent a class being
further subclassed for security reason.
sealed class Abase
{ ….
……
}
sealed class derived : other_class // other than a sealed class
{ ….
……
}

 Sealed class prevents any unwanted extensions to the class.


 It also allows the compiler to perform some optimizations when a method of a sealed
class is invoked
 A sealed class cannot also be an abstract class.

sealed Methods :

 When an instance method declaration included the sealed modifier , the method is said to
be sealed method.
 A sealed method is used to override an inherited virtual method with the same signature.
i.e. sealed modifier is always used in combination with the override modifier.

class A
{ public virtual void fun( )
{ ….
……
}
}
class B : A // other than a sealed class
{ public sealed override void fun( )
{ ….
……
}
}

Here, the sealed method fun ( ) override the virtual method fun( ) defined in class A. any
derived class of B cannot further override the method fun( ).
C# - Polymorphism
The word polymorphism means having many forms. In object-oriented programming
paradigm, polymorphism is often expressed as 'one interface, multiple functions'.

Polymorphism can be static or dynamic. In static polymorphism, the response to a function is


determined at the compile time. In dynamic polymorphism, it is decided at run-time.

Static Polymorphism
The mechanism of linking a methods with an object during compile time itself is called early
binding. It is also called static binding or static linking. It is also called as compile time
polymorphism. C# provides two techniques to implement static polymorphism. They are −

 Method overloading

 Operator overloading

Method Overloading
 You can have multiple definitions for the same method name in the same scope. The
definition of the method must differ from each other by the types and/or the number of
arguments and order of arguments in the argument list. You cannot overload function
declarations that differ only by return type.

Dynamic Polymorphism
 C# allows you to create abstract classes that are used to provide partial class
implementation of an interface. Implementation is completed when a derived class
inherits from it. Abstract classes contain abstract methods, which are implemented by the
derived class. The derived classes have more specialized functionality.

Here are the rules about abstract classes −

 You cannot create an instance of an abstract class

 You cannot declare an abstract method outside an abstract class

 When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.

You might also like