0% found this document useful (0 votes)
24 views13 pages

Part 3

Uploaded by

rohittestuser255
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)
24 views13 pages

Part 3

Uploaded by

rohittestuser255
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/ 13

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 strucutre can't contain a volatile field whereas the class can
12. You can't use sizeof with classes but you can with structures
13. Fields are automatically initialized with classes to 0/false/null wheatheras strucutres are not
14. Fields can't be directley instantiated within structures but classes allow such operations
15. Structures and classes don't adopt the same approach for the System.
What is constructor?

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 parametrized 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. It is invoked at the
time of creating object.

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
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
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

/* 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 ? ( 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. using System.Collections.Generic;
4. using System.Linq;
5. using System.Text;
6. namespace Inheritance
7. {
8. class Program
9. { static void Main(string[] args)
10. {
11. Principal g = new Principal();
12. g.Monitor();
13. Teacher d = new Teacher();
14. d.Monitor();
15. d.Teach();
16. Student s = new Student();
17. s.Monitor();
18. s.Learn();
19. Console.ReadKey();
20. }
21. class Principal
22. {
23. public void Monitor()
24. {
25. Console.WriteLine("Monitor");
26. }
27. }
28. class Teacher : Principal
29. {
30. public void Teach()
31. {
32. Console.WriteLine("Teach");
33. }
34. }
35. class Student : Principal
36. {
37. public void Learn()
38. {
39. Console.WriteLine("Learn");
40. }
41. }
42. }
43. }

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.

You might also like