C# Unit III Notes
C# Unit III Notes
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.
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:
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.
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()
{
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:-
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.
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:
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;
}
// Driver Class
class GFG {
// Main Method
static void Main()
{
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 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,
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,
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.
For example,
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.
In the preceding program the ICar class inherits the features of the two interfaces hence this type of
inheritance is called Multiple 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.
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();
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() ;
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.
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
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 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'.
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.
When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.