0 ratings0% found this document useful (0 votes) 34 views34 pagesC# Series Test Questions
c# series test question answer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
2.12 INTERFACE
2.12.1 What is an interface?
Interfaces are used as super classes whose properties are inherited by classes. It isa user-
defined data type of reference type that declares methods but does not provide implementation
of them. It contains the following features:2.44
C# and .NET Framework
It contains only the signature of methods.
‘The implementation of the method is done in the class that implements the interface,
It is declared using interface keyword.
The class implementing an interface must define all the methods contained inside ay
interface; otherwise the compiler raises an error message
Declaration of an interface
Interface name {
Return-type method-name (parameter list);
Return-type method-name2(parameter list);
Hove”
Return-type method-nameN(parameter list); }
An interface is similar to a class, but with the following major differences:
An interface provides a specification rather than an implementation for it’s members,
This is similar to a pure abstract class, which is an abstract class consisting of only
abstract members.
A class and struct can implement multiple interfaces, while a class can inherit only
from a single class.
A struct can implement an interface, but a struct cannot inherit from a class.
Interfaces are syntactically similar to abstract classes. It specifies what must be done
but not how.
Once the interface is defined, any number of classes can implement it
One class can implement any number of interfaces.
Interface members cannot be declared static’
This supports the aspect of polymorphism, “one interface, multiple methods”
2.12.2 Implementing an Interface
Classes or structs that implement an interface may be said to "fulfill the contract of the
interface." In this example, our 1Delete interface can be implemented by GUI controls that
support the concept of deleting, such as a TextBox, TreeView or the custom GUI control.
public class TextBox : [Delete {
public vold Delete() {..}
}
public class TreeView : IDelete {Object Oriented Aspects of CH 2.45
public void Delete() {...}
}
Ifa class inherits from a base class, then each interface implemented must appear after the
base class:
public class TextBox : Control, IDelete {..}
public class TreeView : Control, IDelete {...,
2.12.3 Using an Interface
An interface is useful when there is a need of multiple classes to share characteristics not
present in a common base class. In addition, an interface is a good way to ensure that these
classes provide their own implementation for the interface member, since interface members
are implicitly abstract.
The following example assumes a form containing many GUI controls (including
some TextBox and TreeView controls) in which the currently focused control is accessed with
the ActiveControl property. When a user clicks Delete on a menu item or toolbar button, the
example tests to see whether ActiveControl implements [Delete, and if so, casts it to [Delete to
call it’s Delete method:
class MyForm {
void DeleteClick() { :
if (ActiveControl is IDelete)
PerformDelete ((IDelete)ActiveControl);
2.12.4 Implementing More Than One Interface
Classes can implement more than one interface. For example, if a Document class can be
stored and it can also be compressed, it is must to implement both the JStorable and
Compressible interfaces. To do so, change the declaration (in the base-list) to indicate that
both interfaces are implemented, separating the two interfaces with commas:
public class Document : IStorable, [Compressible
Having this, the Document class must also implement the methods specified by the
ICompressible interface
public void Compress() -
t2.46 C# and NET Framework
Console, WriteLine(“Implementing the Compress Method");
:
public void Decompress()
t
Console. WriteLine("Implementing the Decompress Method");
}
2.12.5 Extending an Interface
Interfaces may extend other interfaces. For instance:
ISuperDelete : [Delete {
bool CanDelete {get;}
event EventHandler CanDeleteChanged;
}
A control implements the CanDelete property to indicate that it has something to delete and is
not read-only and implements the CanDeleteChanged event to fire an event whenever it's
CanDelete property changes. This framework allows application to ghost its Delete menu item
and toolbar button when the ActiveControl is unable to delete.
2.12.6 Explicit Interface Implementation
If there is a name collision between an interface member and an existing member in the class
or struct, C# allows to explicitly implement an interface member to resolve the conflict. In this
example, we resolve a conflict when implementing two interfaces that both define a Delete
method or 2 methods with same signatures:
public interface IDesignTimeControl {
object Delete();
}
public class TextBox : IDelete, IDesignTimeControl {
void IDelete.Delete() { }
object IDesignTimeControl.Delete() {...}
1 Note that explicitly implementing just one of them would
1 be enough to resolve the conflicty-
Object Oriented Aspects of C#__2.47
unlike implicit interface implementations, explicit interface implementations can't be
pred with abstract Virtual, override, or new modifiers. In addition, while an implicit
dermentation requires the use of the pubic modifier, an explicit implementation has no
imp modifier. However, to access the method, the class or struct must be cast to the
site interface first:
” TextBox th = new TextBox();
[DesignTimeControl idtc = (DesignTimeControl)tb;
[Delete id = (IDelete)th;
idtc.Delete();
id Delete();
Example
Jioomplete program for implementing interface
interface vehicle
* Console.WriteLine(“implementation of vehicle interface”);
{
//2 methods with same signatures
yoid display);
void printQ);
}
interface car
{ void print);
}
class esteem: vehicle, car
f [=
public void display()
(
}
“Explicit interface member implementation
void vehicle.print);
t
Console.writeLine(“éxplicit implementation of vehicle interface");2.48
2.12.7 Abstract class and Interfaces
Abstract classes are syntactically similar to Interfaces. Like any other classes, an abstract class
can be used as an interface in the base class list. However, the interface methods are
implemented as abstract methods.
Example:
Oy
C#.and .NET Framework
void car.print()
€
Console.WriteLine(“explicit implementation of car interface”);
}
static void Main(string[] args)
lt
esteem est = new esteem();
est.displayQ);
est.print(;//error, bcoz implemented explicitly
vehicle v = (vehicle)est;
car c = (car)est;
v.print();
c.print();
}
}
Interface vehicle
t
void display();
}
abstract class car : vehicle
t
public abstract void display();
1 redeclares the interface method as public, no implementation
a
class esteem : car
&Object Oriented Aspects of C# 2.49
void display()
hs
// class esteem overtides and implements the interface method
Therefore by using an interface, the class
not only implements the interface but also uses
another class as base class thus implementin; eat
g in effect multiple inheritance. -,2.6
Object Oriented Aspects of CH 2.21
INDEXER IN C#
The C# introduces the new concept called Indexer. This is very useful for some situation. Let
as discuss something about Indexer,
[Indexer Concept is object act as an array
Indexer an object to be indexed in the same way as an array.]
Indexer modifier can be private, public, protected or internal.
‘The return type can be any valid C# types.
Indexers in C# must have at least one parameter. Else the compiler will generate a
compilation error.
Defining an indexer allows to create classes that act like “virtual arrays." Instances of that
class can be accessed using the [ ] array access operator. Defining an indexer in C# is similar
to define the operator [ ] in C++, but is considerably more flexible. For classes that
encapsulate array- or collection-like functionality, using an indexer allows the users of that
class to use the array syntax to access the class.
Indexers are location indicators and are used to access class objects, just like accessing
elements in an array. They are useful in cases where a class is a container for other objects.
The indexer is implemented through get and set accessors for the [ ] operator
Syntax
this [Parameter]
f
get
t
// Get codes goes here
}
set
f
// Set codes goes here
}
}
For Example
using System;
using System.Collections.Generic;
using System. Text;
namespace Indexers2.22 C# and NET Framework
t
class ParentClass
‘
t
private string[] range = new string[5];
public string this[int indexrange]
{
get
{
return range[indexrange];
}
set
{
range[indexrange] = value;
}
}
}
1 The Above Class just act as array declaration using this pointer
class childclass
f
public static void MainQ)
f
ParentClass obj = new ParentClass(Q);
“The Above Class ParentClass create one object name is obj
obj[0] = "ONE";
objf1] = "TWO";
obj[2] = "THREE",
obj[3] = "FOUR":
obj[4] = "FIVE";
Console. WriteLine("WELCOME TO C# CORNER HOME PAGE\n");
Console. WriteLine("n");
” Console. WriteLine("{0}\n,{1}\n,{2}\n,{3}\n,{4}\n", obj[0], obj 1], objl2h
obj[3], obj{4]);
Console. WriteLine("\n");
Console. WriteLine("ALS.Senthur Ganesh Ram Kumar\n");Console. WriteLine("\n");
Console. ReadLine();
}
}
}
Object Oriented Aspects of C# 2.23
Comparison between Properties and Indexers
Indexers are similar to properties, Exce
of the rules defined for property access;
pt for the differences shown in the following table, all
‘ors apply to indexer accessors as well.
Property
Indexer
This is identified by it’s name.
This is identified by it’s signature.
It is accessed through a simple name or a
member access.
It is accessed through an element access.
It can be a static or an instance member,
It must be an instance member.
A get accessor of a property has no
parameters.
A get accessor of an indexer has the same
formal parameter list as the indexer.
A set accessor of a property contains the
implicit value parameter.
A set accessor of an indexer has the same
formal parameter list as the indexer, in
addition to the value parameter.2.8 INHERITANCE
What is inheritance?
Inheritance is a process by which one class acquires the members of an existing class.
describes a hierarchical relationship between classes.
By the use of inheritance, a class inherits the general attributes and behaviours from
it’s super class and defines only those members that make it unique. Inheritance exposes,
extends, or alters the attributes and behaviours of the super class. A subclass can extend but
cannot narrow it’s super class.
Following are the different forms of inheritance:Object Oriented Aspects of C# 2.31
1. Single inheritance
In single inheritance, a class inher
its fro toe
inherits from class A, class B will acquis a(n on one. super class. For example, if cla
re all the members declared in class A.
A
Y= ——+ Single inheritance
B
Syntax:
Class A {
} :
Class B : A
{// Class B inherits the properties of Class A
}
2, Multilevel Inheritance
In multilevel inheritance, a class inherits from a derived class (or subclass). Multilevel
inheritance is a hierarchy. Assume A is a base class, Class B is derived by A and C is derived
by Class B. This is called as Multilevel inheritance
A
I
Multilevel inheritance
Syntax:
Class A {
}
Class B: A
{// Class B inherits the properties of Base Class A
}
Class C : B //second level derivation2.32 C# and NET Framework
{// Class C inherits the properties of intermediate Class B
3
3. Hierarchical inheritance
In hierarchical inheritance, many sub classes inherit from a single super Class,
example, if classes B, C, and D, inherited from the super class A. Classes B, C, ang Dv
acquire all the members declared in class A. !
A
a
c D
Hierarchical inheritance
Syntax:
Class A {
}
Class B: A .
{// Class B inherits the properties of Base Class A
}
Class C : A
{// Class C inherits the properties of Base Class A
}
4. Multiple Inheritance
In multiple inheritance, a class inherits from several super classes, For example, if class
C inherits from both class A and class B, class C will acquire all the members declared it
class A as well as all the members declared in class B. Multiple inheritance is not directly
implemented by classes in Visual Studio .NET. However, this concept can be implemented
using interfaces. :
A BObject Oriented Aspects of C#_—_2.33
Syntax:
Class A {
?
Class Bf
;
Class C : A, B// Not impossible in C#, but can be implemented using Interface
f
}
2.8.1 Controlling Access using modifiers
The visibility ofa class and it’s members can be restricted through the use of access modifiers
such as public, private, protected, internal, and protected internal.
Public - __allows a member to be accessed by the member methods of other classes.
Private - indicates that the member is visible only to member methods of it’s own
class.
Protected - — the protected keyword extends visibility to methods of derived classes.
Internal - extends visibility to methods of any class in the same assembly.
Note: An assembly is the unit of sharing and reuse in the Common Language Runtime (a
logical DLL). Typically, an assembly is a collection of physical files which is held in a single
directory that includes all the resources (bitmaps, .gif files, etc.) required for an executable,
along with the Intermediate Language (IL) and metadata for that program.
‘The internal protected keyword pair allows access to members of the same assembly
(internal) or derived classes (protected).
Classes as well as their members can be designated with any of these accessibility
levels. If a class member has a different access designation than the class, the more restricted
access applies. Thus, it is possible to define a class, myClass, as follows:
public class myClass
{Mn
protected int myValue;
}
The accessibility for myValve is protected even though the class itself is public. A
public class is one that is visible to any other class that wishes to interact with it. Occasionally,
classes are created that exist only to help other classes in an assembly, and these classes might
be marked internal rather than public.234 C#and NET Framework
program for hierarchical inheritance *
class Flower {
public void display)
{ Console. Writeline(“Flower->Base Class”),
3
class Rose : Flower {
public void show()
{ Console. Writeline("“Rose-> Derived! Class"):
i
class Lilly : Flower {
public void view(
{ Console. Writeline(“Lilly->Derived2 Class”);
}
class Orchids : Flower {
public void print)
{ Console. Writeline( Orchids-> Derived3 Class”);
,
class vehicle {
static void Main(string[] args) {
Rose R= new Rose();
Lilly L = new Lilly);
Orchids O = new Orchids;
Rdisplayg;
Rshow()
Lview0;
Ledisplay; 5
Opring; —Object Oriented Aspects of C# 2.35
Output:
Flower->Base Class
Rose->Derived1 Class
Lilly->Derived2 Class
Flower->Base Class
Orchids->Derived3 Class
2,82 Static Methods and Inheritance
oat Hae He cannot be marked virtual or override. As a result, C#'s virtual
dia ; e_ mech anism ‘cannot be activated for static methods. This is similar to Java's
treatment Is. The use of the base keyword in a static context is not allowed in
ce In the program given below, the Main method calls the static method on the SubClass
class.
WStatic Methods and Inheritance (C#)
using System;
public class SuperClass
{
public static void PublicTest() {
Console. WriteLine("SuperClass PublicTest
}
private static void PrivateTest() {
Console. WriteLine("SuperClass PrivateTest"),;
}
protected static void ProtectedTest() f
Console. WriteLine("SuperClass ProtectedTes|
}
static void Main(string[] args) {
SubClass. PublicTest);2.36 C# and NET Framework
SubClass.ProtectedTest();
SubClass.PrivateTest);
}
}
public class SubClass : SuperClass
iG
public static void PublicTestO {
Console. WriteLine("SubClass PublicTest");
}
private static void PrivateTestQ) {
Console. WriteLine("SubClass PrivateTest");
}
protected static void ProtectedTest() {
Console. WriteLine ("SubClass ProtectedTest");
yy
}
Output
SubClass PublicTest
SuperClass ProtectedTest
SuperClass PrivateTest
Here the Main method is in the SuperClass. The runtime makes the static method call on
SuperClass instead of SubClass.
Note: But a static member ir, C# can't be marked as override, virtual or abstract. However itis
possible to hide a base class static method in a derived class by using the keyword new.
2.8.3 Constructors & Inheritance
¢ Both static and non-static constructors are not inherited to a derived class from a bast
class.
A derived class non-static constructor can call a base class non-static constructor by
using a special function base().
+ It is possible to invoke beth default and parameter ass
fromthe derived'class Pi rized constructors of the base cl
If there is no call for the base class constructor explicitly, the derived class construct!Object Oriented Aspects of C# 2.37
will call the default constructor of th
: ; je base class implicitly when an object of the
derived class is created,
‘This is shown in the program given below,
1 CH Implicit call of base
using System;
class Base
class default constructor
public Base()
{
Console. WriteLine("base constructor");
}
class Derived ; Base
class Myprogram
{
public static void Main()
Derived dl = new DerivedQ.//Displays 'base constructor’
Note : It is possible to call a base class constructor explicitly by using base()
The base Keyword is similar to Java's super keyword. The base keyword can be used
anywhere inside the subclass to invoke a superclass's member. Only public and protected
members can be accessed from the subclass.2.11 POLYMORPHISM, METHOD HIDING AND OVERRIDING IN C#
In object-oriented programming, polymorphism refers to a programming language's ability to
process objects differently depending on their data type or class. More specifically, it is the
ability to redefine methods for derived classes.
The term Poly means many and morph means form. Thus, polymorphism
refers to being able to use many forms of a type without regard to the
details. polymorpihsm ->one name, many form.
It indicates a language’s ability to handle objects differently based on their runtime
type. When objects communicate with one another, they send and receive messages. The
advantage of polymorphism is that the sender of a message doesn’t need to know which class
the receiver is a member of. It can be any arbitrary class. The sending object only needs to be
aware that the receiving object can perform a particular behavior. E
Polymorphism Overview: When a derived class inherits from a base class, it gains all the
methods, fields, properties and events of the base class. To change the data and behavior of a
base class, there are two choices: 1. replace the base member with a new derived member 2.
override a virtual base member ’
For example, a given base class shape, polymorphism enables the programmer to
define different area methods for any number of derived classes such as circles, rectangles and
triangles. Polymorphism is considered to be a requirement of any true object-oriented
programming language.4
2.42 C# and .NET Framework
Ithas 2 types : 1. Compile time 2. Run time
1. Compile time poly: also called overloading 3 types of overloading are:
Constructor overloading (i.e.,with same constructor name and different me
arguments or different data types or both ) of
Function overloading (i.¢.,with same function name and different no of F
arguments or different data types or both)
(©) Operator overloading: example: String s = "James";
@)
(b)
s=s+ "Bond";
2. Runtime poly: It is achieved by overriding parent class method. This js cal
Dynamic method dispatch a
Program Implementing Run-time Polymorphism: DrawDemo.cs
using System;
public class DrawingObject
public virtual void Draw()
Console. WriteLine("I'm just a generic drawing object.");
}
}
/Derived Classes With Override Methods: Line.cs, Circle.cs, and Square.cs
public class Line : DrawingObject
public override void Draw()
Console. WriteLine("I'm a Line."); |
}
}
public class Circle : DrawingObject
public override void Draw()
Console. WriteLine("I'm a Circle.");
}
3
public class Square : DrawingObject
public override void Draw()
ee eee siaObject Oriented Aspects of C# 2.43
Console. WriteLine("I'm
@ Square.");
) ( iquare.");
}
program Implementing Polymorph
‘public class DrawDemo Mom
public static int Main()
Drawing Object[] dObj = new DrawingObject 4];
dObj[0] = new Line;
dObj[1] = new CitcleQ;
dObj[2] = new Squared;
dObj[3] = new DrawingObject(;
foreach (DrawingObject drawObj in dObj)
drawObj.Draw();
return 0;
} :
} ;
* Output: ,
I'ma Line.
I'm a Circle.
I'm a Square..
I'm just a generic drawing object.
The code in this lesson can be compiled with the following command line:
cse DrawDemo.cs DrawingObject.cs Circle.cs Line.cs Square.cs
This relationship between virtual methods and the derived class methods that override
them enables polymorphism.
CH provides an alternative approach for implementing multiple inheritance using interface.2.5 -PROPERTY IN C# CLASS
What are properties?
© Properties are like normal variables, like oth
power and flexibility.
The Set and Get methods are contained inside the property dec laration.
Once the properties are declared, they can be used as if they were fields of the class,
This allows for a very natural syntax when both getting and setting the value of
property
A CH property consists of:
+ Field declaration
«Accessor Methods (getter and setter methods)
Getter methods are used to retrieve the field's value and setter methods are used to modify the
field's value. C# uses a special Value keyword to achieve this .
C#, suggested this approach to retrieve the field's value outside the class, instead of
directly accessing member variables.
‘The following code snippet shows how to create "Property" in a class.
er primitive variables, but with mop
public class Car
fs
1/ private fields.
private string color;Object Oriented Aspects of CH 219
“constructor
public Card
‘
,
public string Color “property
c
get
f
return color; // return the value from private field.
set
f
) color = value; // value is keyword.
3}
The above class has one private field - color. Then there is a "Property" called ‘Color’, which
is used to represent the private field. Note that the field is private and the Property is public.
Each property has two parts :
I. get
2. set
‘The get part is executed when accessing the value of the Property as shown below:
Car car = new Card;
string color = car.Color;
When executed, the above get accessor will return the value stored in the field ‘color’.
‘The set part is executed when assigning a value to the Property as shown below:
Car car = new CarQ;
car.Color = "RED";
When executed, the above set accessor will assign the value "RED" to the private field ‘color’.
(Note that 'value' is a keyword, which will have the value assigned to it.)
So, what is the difference ?
First advantage of using property is, code looks cleaner than the two separate methods.
Itis possible to call a property as if it was a field in the class.
The main’advantage using a Property instead of a public field is it is possible to get a
chance to write few lines of code in the get and set accessors. So, you can perform some
validation or any other logic before returning any values or assigning to the private field.220 CH and NET Framework
See the modified class below:
public class Car
private fields
private string color;
/ constructor
public CarQ
if
public string Color
i
get
f
if (color ==")
return "GREEN";
else
. return color;
set
if (value ==")
thrown new Exception ("Wrong value."):
: else
color = value;
}
3
a
Here we are checking whether there is a valid value in the field ‘color’ before return the value,
If it is empty, we are getting a chance to return a default value ‘Green’. This way, we can make
sure that whoever calls the property ‘Color’ will always get a valid color, never an empty
string.
In the set part, it is possible to do a validation to make sure that always assign a valid
value to the ficld. If assigniny, an empty string to the ‘Color’ property, then there is an
exception (error).
Car car = new CarQ);
car.Color =";
The above code will throw an error because an assignment is made for an empty
string.1.4.8 Type Conversions
‘Type conversion is to convert data from one data type to data of another data type.
Two types of type conversions are given as
1. Implicit conversion (Arithmetic Operations)
2. Explicit conversion (Casting Operations)
1.4.8.1 Implicit Conversion
Ifa compiler converts one type of data into another type of data automatically, it is known as
implicit conversion. There is no data loss in implicit conversion.136 C# and NET Framework
Implicit conversion is also called as automatic type conversion. The destination type rang
should be greater than the source type.
Example
short a = 20;
intb =a; / implicit conversion (widening conversion no data loss)
Sloat c = b; :
1.4.8.2 Expli ‘Conversion
When the data of one type is converted explicitly to another type with the help of so
predefined functions, it is called as explicit conversion and there may be data loss in thal
process because the conversion is forceful (narrowing concept).
Example
- int to short
= int to unit
- unit to int
= float to int
double to long (decimal to any numeric type)
int to char (any numeric type to char)
Casting in compatible types:
Syntax
type var! = (type) var2;
The type in parenthesis is the conversion type. There may be loss of data in casting process, if
is casting to a small type.
i
Example
i. int x = (int) 26.24 // Fractional part of the float value will be lost.
2. | Numeric to string
intx = 0;
string. str = x.ToString(); —_ //x has been converted to string so x ='20"
3. ‘String to integer value
string sir = “20”;
int y = int.Parse(str); // now value of y =20 4Object Oriented Aspects of C# 29
Note:In C#, data ficlds, member functions, properties and events can be declared either as
static or non-static. But indexers in C# can't declared as static.
2.3 Constructors and Destructors:
In C#, (like other Objected Oriented languages) constructor is a method having the same name
as the class. The constructor is called when the object is being created. It can have one or
more parameters.
Why Constructors?
A constructor can be used, where every time an object gets created and if some of the code to
be executed automatically. The code which is wanted to execute must be put in the
constructor.
Description
A constructor is a method that is invoked upon instantiation of a class, known as "instance
constructors". An instance constructor is a member that implements the actions required to
initialize an instance of a class.
Every constructor has the same defining layout:
[access-modifier] constructor_name (parameters)
if,
1/ constructor body
3
© The access-modifier is optional and can be private, public, protected or internal. If no
modifier is supplied, then the default is private.
* The constructor_name of a constructor must be the same as the name of the class.
A constructor can take zero or more arguments as parameters. A constructor with
zero arguments (that is no-arguments) is known as a default constructor. A class can
have more than one constructor, by giving each constructor and a different set of
parameters. This gives the user ability to initialize the object in more than one way.
© The cénstructor body can be used to initialize the object into a known starting state.
* There is no return type for construciors
* In general a constructor’s access modifier is public, this is because the class that is
creating an instance of this class, needs to be able to access the constructor of the
class.oO
C# and NET Framework nts.
ume!
7 it fe arg’
he following class contains a constructor whieh takes SO
4 C# constructor example
using System;
class Complex
{
private int x;
private int Y! :
public Complex(irt +
e
xen
ye.
,
public void displayO
e
Console. WriteLine(s +" + De
3
‘class Myprogram
public static void MainO
Complex cl = new Complex(10, 15);
el.display0:
3
} 7
«the following code segment will display 10+i15 on the command prompt.
Complex el = new Complex (10,15);
. // Displays 10+i15
el.display 0;
omplex is created, it automatically calls the constructor
y. Constructor is mainly used for initializing an object.
culations inside a constructor. The statement inside a
That is when an object of the class C
and initializes it’s data members x and
It is possible to do very complicated cal
constructor can throw exceptions also.
If there is not a constructor with a class, the C# provides a default constructor with an
empty body to create the objects of the class. if there is any own constructor, C# do not
provide the default constructor.- Object Oriented Aspects of C#__2.11
2.3.1 4 parameterized constructor
using System;
class MyClass {
public int x;
public MyClass(int i) ¢
Sea
3
3
public class ParmConsDemo {
public static void Maing) {
MyClass t1 = new MyClass(20);
MyClass 12 = new MyClass(40);
Console. WriteLine(tl.x + "" + 12x);
}
2
2.3.2 Constructor Overloading
As the member functions, constructors can also be overloaded in a class. The overloaded
constructor must differ in their number of arguments.
The following program shows the overloaded constructors in action
1/ C# constructor overloading
class Complex
é
public Complex(int i, int j)
f
i
public Complex(double i, double j)
t
}
Console. WriteLine("constructor with 2 integer arguemets");
Console. WriteLine("constructor with 2 double arguments"),2.12 C#t and NET Framework
publi Complex
Console. WriteLine("no argument constructor”
3
3
class Myprogram
€
public static void MainO
| doplegs ‘constructor with 2 integer arguments’
Complex el = new Complex(10,19): ;
// displays ‘constructor with 2 double argume nts"
Complex c2 = new Complex(2.5,5-0); a
Complex 3 = new Complex; displays ‘ne argument constructor’
}
Ee
mmbers. It is called automaticaly,
2.3.3 Static Constructors
ed to initialize any static data mel
tatic members are referenced. A staji
Therefore cannot be calle
which is created or any s
difiers or have parameters.
A static constructor is us
‘fferentiate the static constructor from the normal
before the first instance
constructor does not take access mo‘
using the new keyword.
The keyword static is used to di
constructors.
Static constructors have the following properties
‘A static constructor does not take access modifiers
A static constructor does not have parameters.
.
A static constructor cannot be overloaded.
faults to the same accessibility as the class itself.
.
led automatically to initialize the class before the firs
Accessibility de!
A static constructor is call
instance which is created or any static members are referenced.
A static constructor cannot access non-static members directly.
¢ Asstatic constructor is not inheritable.
For example
1 C# static constructor
using System;
— 2sObject Oriented Aspects of Cf 2.13
class Complex
f
static Complex()
: Console. WriteLine('static constructor’
class Myprogram
public static void Maing
fe
Complex c;
Console. WriteLine("C sharp"
; © = new Complex);
}
Output +
C Sharp
static constructor
Here the static constructor is called when the class is loaded at the first time. So it can't predict
the exact time and order of static constructor execution. They are called before an instance of
the class is created, before a static member is called and before the static constructor of the
derived class is called.
‘The static constructor of a base class cannot inherited to the derived class.
2.3.4 Private Constructors
In C#, constructors can be declared as public, private, protected or internal. When a class
declares only private constructors, it is not possible other classes to derive from this class or
create an instance of this class. Private constructors are commonly used in classes that contain
only static members. However a class can contain both private and public constructor and
objects of such classes can also be created, but not by using the private constructor.
The following is a valid program in C#
1 C# constructor both private & public
using System;
class Complex
é
private Complex(int i, int j)
t
Console. WriteLine("constructor with 2 integer arguments")2.14 C# and .NET Framework
_ private Complex() ;
constructor’);
Console.WriteLine("no argument
}
}
class MyClient
f
public static void MainQ
Complex c3 = new Complex;
}
}
ince i i rivate constructors
However the above program do not compile, since it contain only Pp’her classes, an abstract class
2.12.7 Abstract class and Interfaces
the interface methods are
Abstract classes are syntactically similar to Interfaces. Like any ot
can be used as an interface in the base class list. However,
implemented as abstract methods.
Example:
Interface vehicle
te
void display0;
Hu
abstract class car : vehicle
é
public abstract void display);
// redeclares the interface method as public, no implementation
}
class esteem : car
fObject Oriented Aspects of C# 2.49
void display)
é
// class esteem overtides and implements the interface method
y
Therefore by using an interface, the class not only implements the interface but also uses
another class as base class thus implementing in effect multiple inheritance. ~