100% found this document useful (3 votes)
505 views29 pages

CIT 834 Past Questions and Answers by Henry Finebone

Uploaded by

irabiu2059
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
100% found this document useful (3 votes)
505 views29 pages

CIT 834 Past Questions and Answers by Henry Finebone

Uploaded by

irabiu2059
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/ 29

Questions

Answers
Codes in answers

CIT 834 (OBJECT-ORIENTED PROGRAMMING USING C#) PAST QUESTIONS AND


ANSWERS BY HENRY FINEBONE
1. Explain object-oriented programming and state its characteristics.
Object-oriented programming is a programming approach that provides a way of modularizing programs
by creating partitioned memory area for both data and functions that can be used as templates for creating
copies of such modules on demand. Thus, an object is considered to be a partitioned area of the computer
memory that stores data and set of operations that can access that data. Since the memory partitions are
independent, the objects can be used in a variety of different programs without modifications. (OOP) was
first developed in the 1960s, as a programming concept to help software developers build high quality
software. Object-orientation is also a concept which makes developing of projects easier. Consequently,
object-oriented programming attempts to solve the problems with only one approach; dividing the
problems in sub-modules and using different objects. Objects of the program interact by sending messages
to each other.
Characteristics:
1. Emphasis is on data rather than procedure.
2. Programs are divided into what are known as objects.
3. Data structures are designed such that they characterize the objects.
4. Functions that operate on the data of an object are tied together in the data structure
5. Data is hidden and cannot be accessed by external functions.
6. Objects may communicate with each other through functions.
7. New data and functions can be easily added whenever necessary.
8. Follows bottom-up approach in program design.

2. Briefly discuss the following concepts in object-oriented programming:


(i) Polymorphism
Polymorphism refers to the ability to take more than one form. An operation may exhibit different
behaviours in different instances. The behaviour depends upon the types of data used in the operation. For
example, consider the operation of addition of two numbers; the operation will generate a sum. If the
operands are strings, then the operation would produce a third string by concatenation. Polymorphism
plays an important role in allowing objects having different internal structures to share the same external
interface. This means that a general class of operations may be accessed in the same manner even though
specific actions associated with each operation may differ.

(ii) Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects of another class.
For example, the bird ‘robin’ is a part of the class “flying bird’ which is again a part of the class ‘bird’. The
principle behind this sort of division is that each derived class shares common characteristics with the
class from which it is derived. The concept of inheritance provides the idea of reusability. This means that
we can add additional features to an existing class without modifying it. This is possible by deriving a new
class from the existing one. The new class will have the combined features of both the classes.
(iii) Data abstraction and encapsulation
Data abstraction refers to the act of representing essential features without including the background
details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes
such as size, weight and cost, and functions to operate on these attributes. They encapsulate all the
essential properties of the objects that are to be created.
Encapsulation, also known as data hiding, is an important object-oriented programming concept. It is the
act of concealing the functionality of a class so that the internal operations are hidden from the
programmer. With correct encapsulation, the developer does not need to understand how the class
actually operates in order to communicate with it via its publicly available methods and properties; known
as its public interface.

3. In order to assess your expertise in Object-Oriented Programming using C# Programming, you are required
to write a standard C# program to carry out two mass calculations and provide the output of the call count
property, where the Density is given as 40; Volume1 = 120; Volume2 = 140.
{
int density = 40; int
volume = 120; int
volume2 = 140;
int mass1 = MassCalculator.CalculateMass(density, volume);
int mass2 = MassCalculator.CalculateMass(density, volume2);
int calls = MassCalculator.CallCount;
Console.WriteLine("Mass1: {0}", mass1); // Outputs "Mass1: 5000"
Console.WriteLine("Mass2: {0}", mass2); // Outputs "Mass2: 9000"
Console.WriteLine("Calls: {0}", calls); // Outputs "Calls: 2"
}

4. Outline the procedure involved in constructing a simple Two-Dimensional Vector Class having K and L as
its properties.
private int _k, _l;
public Vector(int k, int l) { _k = k; _l = l; }
public int K
{
get { return _k; }
set { _k = value; }
}
public int L
{
get { return _l; }
set { _l = value; }
}

5. If a specific integer is given as 8, write down a simple C# Program to compute and output the square of this
integer.
static void Main(string[] args)
{
int squareMe = 8;
Console.WriteLine(Calculate.Square(squareMe));
}
/* OUTPUT
Integer Square calculated
64
*/

6. Give a concise explanation of the concept of operator overloading.


Operator overloading is simply the process of adding operator functionality to a class. This allows you to
define exactly how the operator behaves when used with your class and other data types. This can be
standard uses such as the ability to add the values of two vectors, more complex mathematics for
multiplying matrices or non-arithmetic functions such as using the + operator to add a new item to a
collection or combine the contents of two arrays. Multiple overloaded versions of operators may also be
created to provide different functionality according to the data types being processed, in a similar manner
to the varying signatures of method overloading.

7. State at least one application of the notion of operator overloading.


Adding the values of two vectors, more complex mathematics for multiplying matrices or non-arithmetic
functions such as using the + operator to add a new item to a collection or combine the contents of two
arrays.

8. What is the role of the signature with respect to methods in C# Programming.


The signature defines the name and the set of parameters for the method.

9. What steps would you adopt in creating a new project named ‘Practise.cs’?
1. Select File -> New project
2. From the project dialog, select the Console application
3. This is the most basic application type on a Windows system
4. Click Ok
5. Visual C# Express creates a new project for you, including a file called Program.cs.

10. Give a brief explanation of the term ‘binary operator’.


The binary operator is a type of operator that requires two values to work with. These include the simple
arithmetic operators such as +, -, *, / and %.

11. Write down two (2) classic components of a binary operator.


1. result-type
2. operand

12. In simple terms, describe how static methods are called in C#.
A static method is declared using a similar syntax to a class method. The 'static' keyword is used in the
declaration to indicate the modified behaviour. To add the mass calculation method to the new class,
insert the following code:
13. State the code for accomplishing the following in C#:
(i) Adding a mass calculation method to the new class
public static int CalculateMass(int density, int volume)
{
return density * volume;
}

(ii) Adding a read-only call count property to a class.


public static int CallCount
{
get
{
return _callCount;
}
}

14. Go through the source code carefully and answer the questions that follow:

(i) Give a brief description of the term ‘keyword’.


Keywords are predefined, reserved identifiers that have special meanings to the compiler. They can't be
used as identifiers in your program unless they include @ as a prefix. For example, @if is a valid identifier,
but if isn't because if is a keyword.

(ii) Write down the keyword in the source code provided.


"using"

(iii) State the main role of the keyword you have specified.
This keyword “using” imports a namespace.

15. Outline the steps required to build a new project named ‘Abuja’ and setup a form using the Windows
Application template.
First, we create a new Console Application project
Steps:
1. Open visual studio --> under file menu select the option new -->select project
2. On the left side, select Templates --> select Visual C# and select the Console Application. Name the
application ‘Abuja’.
3. After creating an application, by default, it will create a Program.cs file.
4. In C# programming the main method is where Program start execution it is the main entry point of the
program that executes all the objects and invokes methods to execute.
5. Click on F5 and execute the project, and follow the console window.
Then we create the form using the Windows Application template.
Steps:
1. Click the File menu again.
2. This time, select New Project from the menu. When you do, you'll see the New Project dialogue box
again.
3. Select Windows Application from the available templates. Keep the Name as ‘Abuja’ and then click OK.
When you click OK, a new Windows Application project will be created for you.

16. Based on the premise that you have successfully completed the course in Object-Oriented Programming
using C#, a newly registered learner has just approached you for guidance on how to build a C# sample
in a Microsoft.NET 2.0 SDK Framework. Outline the procedure you would adopt in order to accomplish
this requisite assignment.
1. Open the Microsoft .NET Framework 2.0 SDK command prompt (from the Windows Start menu, select
Programs > Microsoft .NET Framework SDK v2.0 > SDK Command Prompt. The command prompt
launches.
2. Navigate to the sub-directory containing the Build2005.cmd and other files: cd
%SDKHOME%\samples\DotNet
3. Run the Build2005.cmd to generate new stubs and compile into an assembly. Simply enter the name of
the script at the command prompt: build2005
4. Test your development workstation.

17. Give a short description of the following features in a common FCL library:
(i) Interop
This provides backward-compatibility with COM and Win32 code.

(ii) Thread management


This allows you to run multiple threads of execution

(iii) Type loading


This finds and loads assemblies and types

18. Define .NET Framework.


.NET Framework is a software development framework for building and running applications on
Windows. .NET Framework is part of the .NET platform, a collection of technologies for building apps for
Linux, macOS, Windows, iOS, Android, and more.

19. State specific setup instructions upon which C# development varies.


Specific setup instructions will vary, depending on whether your development workstation already
meets some or all of the requirements, and whether you plan to use the provided samples.
To set up a development workstation to use C#:
1. Install the Microsoft Visual programming environment, such as Microsoft Visual Studio 2005, Microsoft
Visual Studio .NET 2003, or Microsoft Visual C#. VMware recommends using Microsoft Visual Studio
2005, which includes the required .NET Framework 2.0 and improved versions of Web-services-client
tools.
2. Obtain the Microsoft .NET Framework 2.0 or Microsoft .NET Framework 1.1. If you have been using
Microsoft development tools for any length of time, it’s likely you already have what’s needed. If not, you
can obtain Microsoft .NET Framework from Microsoft, at: http://msdn.microsoft.com.
3. Obtain the VMware Infrastructure SDK (VI SDK) package from VMware Web site:
http://www.vmware.com/download/sdk/
4. Unpack the various components into appropriate sub-directories. Use Microsoft defaults for Microsoft
Visual Studio, Microsoft.NET Framework, and Microsoft .NET Framework SDK. To ensure that all paths
to all tools (wsdl.exe, csc.exe) are set correctly, it’s best to execute the command script from the Microsoft
.NET 2.0 SDK command prompt, available from the .NET SDK menu.
To build the C# samples:
1. Open the Microsoft .NET Framework 2.0 SDK command prompt (from the Windows Start menu, select
Programs > Microsoft .NET Framework SDK v2.0 > SDK Command Prompt. The command prompt
launches.
2. Navigate to the sub-directory containing the Build2005.cmd and other files: cd
%SDKHOME%\samples\DotNet
3. Run the Build2005.cmd to generate new stubs and compile into an assembly. Simply enter the name of
the script at the command prompt: build2005
4. Test your development workstation.

20. Study the following C#.NET code snippet.


namespace NounConsoleApplication
{
class SampleProgram
{
static void Main(string[ ] args)
{
object[] o = new object[] {"1", 4.0, "Abuja", 'B'};
fun (o);
}
static void fun (params object[] obj)
{
for (int i = 0; i < obj.Length-1; i++)
Console.Write(obj[i] + " ");
}
}
}
(a) Explain what namespace refers to.
A namespace is a collection of classes. It is a way to group related code together.

(b) What will be the output of the code?


1 4 Abuja

21. In C#, what is the role of Method Overloading?


Method overloading is a technique which allows the programmer to define many methods with the same
name but with a different set of parameters.
22. Study the following C# code and answer the question that follows:
namespace NounConsoleApplication
{
class SampleProgram
{
static void Main(string[ ] args)
{
int a = 5;

int s = 0, c = 0;
s, c = fun(a);
Console.WriteLine(s +" " + c) ;
}
static int fun(int x)
{
int ss, cc;
ss = x * x; cc = x * x * x;
return ss, cc;
}
}
}
Select, at most, two (2) correct statements among the following:
(i) An error will be reported in the statement s, c = fun(a); since multiple values returned from a function
cannot be collected in this manner.
(ii) It will output 25 125.
(iii) It will output 25 0.
(iv) It will output 0 125.
(v) An error will be reported in the statement return ss, cc; since a function cannot return multiple values.
(i) An error will be reported in the statement s, c = fun(a); since multiple values returned from a function
cannot be collected in this manner.
(v) An error will be reported in the statement return ss, cc; since a function cannot return multiple values.

23. Select a combination of correct statements about subroutines usage in C#.NET? (Choose only from the
options (A, B, C, D) provided.
(i) If we do not return a value from a subroutine then a value -1 gets returned.
(ii) Subroutine definitions cannot be nested.
(iii) Subroutine can be called recursively.
(iv) To return the control from middle of a subroutine exit subroutine should be used.
(v) Subroutine calls can be nested.
A. [(i), (ii), (iii)] B. [(ii), (iii), (v)] C. [(iii), (v)] D. [(iii), (iv)]
B. [(ii), (iii), (v)]
24. Define what constructors are and their role in C# programming.
A constructor is a special class member that is executed when a new object is created. The constructor's
job is to initialise all of the public and private state of the new object and to perform any other tasks that
the programmer requires before the object is used.

25. Write the correct syntax for adding two (2) integer variables to a Parallelogram class.
class Parallelogram
{
private int _base;
private int _height;
}

26. Study the figure below carefully and answer the questions that follow:

(i) Give any 2 reasons why this application is considered suitable for learning Object-Oriented
Programming using the C# and utility programs?
1. This application is ideal for learning C# development because the user interface is so simple.
2. Console application is very useful for utility programs that require little or no user interaction.

(ii) State the procedure involved in creating a new Console Application project.
A Console Application is an application that takes input and displays output at the console. This console
looks like a DOS window.
Creating a new Console Application project:
1. Open visual studio --> under file menu select the option new -->select project
2. On the left side, select Templates --> select Visual C# and select the Console Application. Give some name
for the application,
3. After creating an application, by default, it will create a Program.cs file.
4. In C# programming the main method is where Program start execution it is the main entry point of the
program that executes all the objects and invokes methods to execute.
5. Click on F5 and execute the project, and follow the console window.

27. Enumerate the steps required to build a novel class to represent a triangle. The class should be created in
such a way that it will define the triangle's height, base-length and area.
public class Triangle
{
private int _height;
private int _baseLength;
public int Height
{
get
{
return _height;
}
set
{
if (value < 1 || value > 100)
{
throw new OverflowException();
}
_height = value;
}
}
public int BaseLength
{
get
{
return _baseLength;
}
set
{
if (value < 1 || value > 100)
{
throw new OverflowException();
}
_baseLength = value;
}
}
public double Area
{
get
{
return _height * _baseLength * 0.5;
}
}
}
28. Within the context of programming using C#, what solution would you proffer, in the event that a web
service from Microsoft .NET client sample does not connect through a proxy server?
Try a different server on the same subnet as the client.

29. What determines the type of setup instruction used for C# Development?
Whether your development workstation already meets some or all of the requirements, and whether you
plan to use the provided samples.

30. Explain the concept of ‘private method’ within the context of Object-Oriented Programming using C#.
To provide for encapsulation, where the internal functionality of the class is hidden, some methods will
be defined as Private. Methods with a private protection level are completely invisible to external classes.
This makes it safe for the code to be modified to change functionality, improve performance, etc. without
the need to update classes that use the public interface. To define a method as private, the private
keyword can be used as a prefix to the method. Alternatively, using no prefix at all implies that the method
is private by default.

31. Demonstrate with example how parameters are being passed and received by a method.
The parameters a method receives are also provided in a set of parentheses, but the type and a name for
each parameter must be specified. The name does not have to be the same as the argument. For example:
public static void PassesInteger()
{
int fortyFour = 44;
TakesInteger(fortyFour);
}
static void TakesInteger(int i)
{
i = 33;
}
Here a method called PassesInteger passes an argument to a method called TakesInteger. Within
PassesInteger, the argument is named fortyFour, but in TakeInteger, this is a parameter named i. This
parameter exists only within the TakesInteger method.

32. Declare three (3) methods named; RegisterCourse, TakeExam, and GetResults with no parameters and
return no value under a class named student.
class Student
{
public void RegisterCourse(int numberofcourses) { }
public void TakeExam() { }
public int GetResults(int scores) { return 0; }
}

33. Refer to question 32 above, call the method with the student named “Peter” with the following arguments;
assuming he registered 2 courses, took exams on those two courses and had 60 and 57 respectively as
result.
Student Peter = new Student();
Peter.RegisterCourse(2);
Peter.TakeExam();
Peter.GetResults(60, 57);

34. Write a C# program to display the text “NOUN is a citadel of learning” using the WriteLine method.
using System ;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("NOUN is a citadel of learning");
Console.ReadLine();
}
}
}

35. Show how to access properties of instantiated objects.


Properties of instantiated objects are accessed using the object name followed by the member access
operator (.) and the property name. The property can be read from and written to using similar syntax
as for a standard variable. To demonstrate this, consider the following example code, added to the Main
method of the program. It creates two objects based upon the Rectangle class and assigns and reads their
properties individually. When trying to assign an invalid height to a rectangle, an exception is thrown by
the validation code.
static void Main(string[] args)
{
Rectangle rect = new Rectangle();
rect.Width = 50;
rect.Height = 25;
Rectangle square = new Rectangle();
square.Height = square.Width = 40;
Console.WriteLine(rect.Height); // Outputs "25"
Console.WriteLine(square.Width); // Outputs "40"
rect.Height = 25; // Throws the validation exception.
}

36. Name 5 common FCL libraries with their descriptions.


1. Debugging Facilities: This is used for making it easier to debug code.
2. Exception management: This allows you to write code to create and handle exceptions.
3. Execution management: This manages the execution of code
4. Garbage collection: This caries out automatic memory management and garbage collection.
5. Interop: This gives backward-compatibility with COM and Win32 code.

37. Outline the steps taken to add a C# class using solution explorer.
1. In Solution Explorer, right-click the project name and click Add, and then click Add Class.
The Add New Item dialog box appears with the C# Class icon already selected.
2. In the dialog box, enter a class name in the Name field and click Open.
The new class is added to your project.

38. Give two (2) steps of using the static property.


1. The property name is preceded by the class name and the member access operator (.).
2. To demonstrate, adjust the Main method to perform two mass calculations and output the call count
property.

39. Outline the procedure to set up a development workstation to use C#.


1. Install the Microsoft Visual programming environment, such as Microsoft Visual Studio 2005, Microsoft
Visual Studio .NET 2003, or Microsoft Visual C#. VMware recommends using Microsoft Visual Studio
2005, which includes the required .NET Framework 2.0 and improved versions of Web-services-client
tools.
2. Obtain the Microsoft .NET Framework 2.0 or Microsoft .NET Framework 1.1. If you have been using
Microsoft development tools for any length of time, it’s likely you already have what’s needed. If not, you
can obtain Microsoft .NET Framework from Microsoft, at: http://msdn.microsoft.com
3. Obtain the VMware Infrastructure SDK (VI SDK) package from VMware Web site:
http://www.vmware.com/download/sdk/
4. Unpack the various components into appropriate sub-directories. Use Microsoft defaults for Microsoft
Visual Studio, Microsoft.NET Framework, and Microsoft .NET Framework SDK. To ensure that all paths
to all tools (wsdl.exe, csc.exe) are set correctly, it’s best to execute the command script from the Microsoft
.NET 2.0 SDK command prompt, available from the .NET SDK menu.

40. Identify a general form of a class definition for a class named “payment” and declare 4 instance variables
named; basicpay, houseallowance, transallowance and tax.
class payment {
// declare instance variables
access type basicpay;
access type houseallowance;
access type transallowance;
access type tax;
// ...
access type varN;
// declare methods
access ret-type method1(parameters) {
// body of method
}
access ret-type method2(parameters) {
// body of method
}
access ret-type method3(parameters) {
// body of method
}
access ret-type method4(parameters) {
// body of method
}
// ...
access ret-type methodN(parameters) {
// body of method
}
}

41. Show how a static method is declared with a formula to calculate the area of a rectangle, use values of
your choice to call the method.
Declaring the static method:
public static int CalculateArea(int length, int breadth)
{
return length* breadth;
}
Calling the static method:
static void Main(string[] args)
{
int length = 15;
int breadth = 10;
int area = AreaCalculator.CalculateArea(length, breadth);
Console.WriteLine("Area: {0}", area); // Outputs "Area: 150"
}

42. Analyse the differences and similarities of a constructor and a destructor.


Differences:
1. Constructors help allocate memory to an object while destructors deallocate the memory of an object.
2. Constructors can take arguments while destructors don't take any arguments.
3. Constructors are called automatically when an object is created, whereas destructors are called
automatically when the block is exited or when the program terminates.
4. Constructors can be overloaded while destructors cannot be overloaded.
Similarities:
1. Both constructors and destructors are associated with objects.
2. Both constructors and destructors do not return any value.
3. Both constructors and destructors are called automatically.
43. Syntactically define C# indexer page.
<modifier> <return type> this [argument list]
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}

44. How is static property different from private variable?


A private variable is created for each class object, whereas a static property is created only once and
shared among all class objects.

45. Demonstrate with examples the relationship between a class and an object.
The class is the abstract concept for an object that is created at design-time by the programmer. While
objects based upon the class are the concrete instances of the class that occur at run-time. For example,
the Car class will define that all cars have a make, model and colour. Only at run-time will an object be
instantiated as a Red.

46. Demonstrate how .net framework manages memory through garbage collection.
When objects are created they occupy some memory. As memory is a limited resource, it is important
that once the objects are no longer required, they are cleaned up and their memory is reclaimed. The
.NET framework uses a system of garbage collection to perform this activity automatically so that the
developer does not need to control this directly.

47. Demonstrate with an example of a car the concept of a state of an object.


The state of an object is the property which describes its individual data or unique configuration. In the
example of a car object, methods allow us to accelerate or decelerate but the state, described in
properties, allows us to determine the actual speed and to describe one car object as red and another as
blue. This information creates a real differentiation between the two objects.

48. Justify the use of encapsulation in Object Oriented Programming.


With correct encapsulation, the developer does not need to understand how the class actually operates
in order to communicate with it via its publicly available methods and properties; known as its public
interface.

49. Appraise the usefulness of static constructors.


A static constructor is used to initialise the static state of a class when it is first used. A static constructor
is always declared as private and as such may not be directly called by a program.
50. The area of a triangle with base of 10cm and height of 20 cm is to be calculated. Declare a static method
that will aid in the calculation.
public static int CalculateArea(int base, int height)
{
return (base * height)/2;
}

51. Write a C# program to add increment operator and test the program with (10,15) and display the results
on console.
public static Vector operator ++(Vector v)
{
v.X++;
v.Y++;
return v;
}
To test these operators, update and execute the Main method:
static void Main(string[] args)
{
Vector v1 = new Vector(10, 15);
v1++;
Console.WriteLine("({0},{1})", v1.X, v1.Y); // Outputs "(11,16)"
}

52. Illustrate syntactically, the declaration of a binary operator and explain each line of the illustration.
public static result-type operator binary-operator (
op-type operand,
op-type2 operand2
)
This initially appears to be a rather complex declaration but in fact is quite simple. The declaration starts
with public static as all operators must be declared as such. Other scopes are not permitted and neither
are non-static operators.
The result-type defines the data type or class that is returned as the result of using the operator. Usually
this will be the same type as the class that it is being defined within. However, that need not be the case
and it is perfectly valid to return data of a different type.
The operator keyword is added to tell the compiler that the following binary-operator symbol is an
operator rather than a normal method. This operator will then process the two operand parameters, each
prefixed with its data type (op-type and op-type2). As least one of these operands must be the same type
as the containing class.

53. Describe with an example how a reference type is created with the class keyword.
public class SampleRefType
{
public int value;
}
54. Declare a static method with a formula to calculate the area of a parallelogram. Use values of your choice
to call the method.
Declaring the static method:
public static int CalculateArea(int base, int height)
{
return base * height;
}
Calling the static method:
static void Main(string[] args)
{
int base = 8;
int height = 12;
int area = AreaCalculator.CalculateArea(base, height);
Console.WriteLine("Area: {0}", area); // Outputs "Area: 96"
}

55. Identify the relationship between polymorphism and object-oriented programming.


One of the key features of object-oriented programming is polymorphism. Polymorphism permits objects
to behave in different ways according to the manner in which they are used. One part of polymorphism
is the ability for a method to behave differently according to the types and number of parameters that
are passed to it. This is achieved through method overloading.

56. Write a C# program to display the text “Nigeria is a great country” using the WriteLine method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Nigeria is a great country ");
Console.ReadLine();
}
}
}

57. Identify five (5) CLR features with their descriptions.


1. Interop: This gives backward-compatibility with COM and Win32 code.
2. Thread management: This allows you to run multiple threads of execution.
3. Type loading: Thus finds and loads assemblies and types.
4. Exception management: This allows you to write code to create and handle exceptions.
5. Execution management: This manages the execution of code.

58. Give the procedure to build the C# samples.


1. Open the Microsoft .NET Framework 2.0 SDK command prompt (from the Windows Start menu, select
Programs > Microsoft .NET Framework SDK v2.0 > SDK Command Prompt. The command prompt
launches.
2. Navigate to the sub-directory containing the Build2005.cmd and other files: cd
%SDKHOME%\samples\DotNet
3. Run the Build2005.cmd to generate new stubs and compile into an assembly. Simply enter the name of
the script at the command prompt: build2005
4. Test your development workstation.

59. Demonstrate how a method can be defined to provide encapsulation.


To provide for encapsulation, where the internal functionality of the class is hidden, some methods will
be defined as Private. Methods with a private protection level are completely invisible to external classes.
This makes it safe for the code to be modified to change functionality, improve performance, etc. without
the need to update classes that use the public interface. To define a method as private, the private
keyword can be used as a prefix to the method. Alternatively, using no prefix at all implies that the method
is private by default. The following method of the car class is a part of the internal implementation not
the public interface so is defined as being private.
private void MonitorOilTemperature()
{
// Internal oil temperature monitoring code...;
}

60. List the process of programming in an Object-Oriented Language.


1. Creating classes that define objects and their behaviour.
2. Creating objects from class definitions.
3. Establishing communication among objects.

61. Explain how Microsoft.Net is standardized.


.NET has been standardized by both the European Computer Manufacturers Association (ECMA) and the
Open Standards Institute (OSI). The standard is referred to as the Common Language Infrastructure (CLI).
Similarly, the standardized term for IL is Common Intermediate Language (CIL).

62. Justify the importance of garbage collection in the process of object creation.
When objects are created they occupy some memory. As memory is a limited resource, it is important
that once the objects are no longer required, they are cleaned up and their memory is reclaimed. The
.NET framework uses a system of garbage collection to perform this activity automatically so that the
developer does not need to control this directly.

63. Give the following information about static property:


(i) Condition for adding static property to a class
The declaration must include the 'static' keyword to modify the property's behaviour.
(ii) Condition for using a static property.
The property name must be preceded by the class name and the member access operator (.).

64. Create syntactically a new addition operator for the Vector class and instantiate two vector objects v1 and
v2 with values of (10,16) and (4,18) respectively, add them together and give the result.
public static Vector operator +(Vector v1, Vector v2)
{
return new Vector(v1.X + v2.X, v1.Y + v2.Y);
}
We can now test the Vector's new operator by modifying the program's main method. The following
program instantiates two Vector objects, adds them together and outputs the values of the resultant
Vector's X and Y properties.
static void Main(string[] args)
{
Vector v1 = new Vector(10, 16);
Vector v2 = new Vector(4, 18);
Vector v3 = v1 + v2;
Console.WriteLine("({0},{1})", v3.X, v3.Y); // Outputs "(14,34)"
}

65. Differentiate between a single inheritance and multiple inheritance.


In single inheritance, a subclass may only inherit functionality from a single base class while multiple
inheritance permits a subclass to have two or more superclasses.

66. What are the requirements for Web services client application?
1. Development environment for C#, such as Microsoft Visual C#, Microsoft Visual Studio 2003, or
Microsoft Visual Studio 2005.
2. Microsoft .NET Framework, specifically Microsoft .NET Framework 2.0 (which is included with
Microsoft Visual Studio 2005).
3. Microsoft .NET Framework 2.0 Software Development Kit. Depending on the specific version of the
Microsoft Visual Studio and Microsoft .NET Framework that you use, you may need to also specifically
install the Microsoft .NET Framework 2.0 software development kit, which includes the command-line
C# compiler (csc.exe).

67. State three (3) basic steps involved in Object-Oriented Programming.


1. Creating the Program. The programmer defines classes that describe objects that the program will use
when it is running.
2. Compiling the Program. The program is compiled into bytecode.
3. Running the Program.

68. Write a simple program that displays “Hello World”.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
Console.ReadLine();
}
}
}

69. Create a class that represents a triangle with the definition of its properties: height, base-length and area.
static void Main(string[] args)
{
Triangle triangle = new Triangle();
Console.WriteLine("Height:\t{0}", triangle.Height);
Console.WriteLine("Base:\t{0}", triangle.BaseLength);
Console.WriteLine("Area:\t{0}", triangle.Area);
}
/* OUTPUT
Triangle constructor executed
Height: 1
Base: 1
Area: 0.5
*/

70. Using an example, state the code for the execution of a constructor.
The newly added constructor replaces the default constructor and is executed automatically when a new
Triangle is instantiated. This can be tested by adding some code to the console application's Main method.
Add the following code and execute the program to test the results and to see that the height and base-
length are set correctly.
static void Main(string[] args)
{
Triangle triangle = new Triangle();
Console.WriteLine("Height:\t{0}", triangle.Height);
Console.WriteLine("Base:\t{0}", triangle.BaseLength);
Console.WriteLine("Area:\t{0}", triangle.Area);
}
/* OUTPUT
Triangle constructor executed
Height: 1
Base: 1
Area: 0.5
*/

71. Give a concise explanation of the concept of Polymorphism as it relates to inheritance and upcasting.
When using inheritance, polymorphism is achieved when an object of a derived class is substituted where
an instance of its parent class is expected. This uses a process known as upcasting. With upcasting, the
object of the more specialised class is implicitly cast to the base class type required.

72. State the advantages and five (5) areas of application of object-oriented programming.
Advantages:
1. We can eliminate redundant code and extend the use of existing classes through inheritance.
2. We can build programs from the standard working modules that communicate with one another, rather
than having to start writing the code from scratch. This leads to saving of development time and higher
productivity.
3. The principle of data hiding helps the programmer to build secure programs that cannot be invaded by
code in other parts of the program.
4. It is possible to have multiple instances of an object to coexist without any interference.
5. It is possible to map objects in the problem domain to those in the program.
6. It is easy to partition the work in a, project based on objects.
7. The data-centered design approach enables us to capture more details of a model in implementable
form.
8 Object-oriented systems can be easily upgraded from small to large systems.
9. Message passing techniques for communication between objects makes the interface descriptions with
external systems much simpler.
10. Software complexity can be easily managed.
Application areas:
1. Real-time systems
2. Simulation and modeling
3. Object-oriented databases
4. Hypertext, hypermedia and expert text
5. AI and expert systems
6. Neural networks and Parallel programming Decision support and office automation systems
7. CIM/CAM/CAD systems

73. Explain the types of inheritance in modern programming languages.


1. Single Inheritance: C# and other .NET languages use single inheritance. This means that a subclass may
only inherit functionality from a single base class.
2. Multiple Inheritance: This permits a subclass to have two or more superclasses. In this situation the
derived class inherits functionality from several base classes. Multiple inheritance is not supported by C#
or the .NET framework. However, this does not stop a class from providing many public interfaces.

74. State with an example the procedure to demonstrate inheritance.


To begin, create a new console application named "InheritanceDemo". Create a class file named "Vehicle"
and add the following code to the new class to provide a Speed property and Accelerate and Decelerate
methods to all vehicles:
private int _speed; // Miles per hour
public int Speed
{
get
{
return _speed;
}
}
public void Accelerate(int mph)
{
_speed += mph;
}
ssss
public void Decelerate(int mph)
{
_speed -= mph;
}

75. Enumerate two (2) conditions on which the specific setup instructions used for C# development variation
will depend on.
1. Whether your development workstation already meets some or all of the requirements.
2. Whether you plan to use the provided samples.

76. State the characteristics of subroutines usage in C#.NET.


1. Subroutine definitions cannot be nested.
2. Subroutine can be called recursively.
3. Subroutine calls can be nested.

77. Explain nullable types in C#.


The Nullable type allows you to assign a null value to a variable. Nullable types introduced in C#2.0 can
only work with Value Type, not with Reference Type. The nullable types for Reference Type is introduced
later in C# 8.0 in 2019 so that we can explicitly define if a reference type can or can not hold a null value.
This helped us to tackle the issue of NullReferenceException without using conditionals.

78. Distinguish a struct from a class.


Structs are value types, allocated either on the stack or inline in containing types while classes are
reference types, allocated on the heap and garbage-collected.

79. List any four (4) features of a typical C# program.


1. Object-oriented language
2. Simplicity
3. Interoperability
4. Consistency
80. What are reference types in C#? Give two (2) examples.
A reference type variable contains a reference to data stored in memory, also known as the heap. The
heap is most often used for data that has a longer life.
Examples:
1. Classes
2. Interfaces

81. Identify the base class for all exceptions in C#.


Exception class

82. Describe how you will debug a C# code.


Put the semicolon back at the end of the line. Now click ‘Debug’ from the menu at the top of Visual C#
Express. From the Debug menu, select ‘Start Debugging’.

83. Correct the errors in the following piece of C# code.


String _Second semester:
Second semester = Textbox.Text.

string Secondsemester;
Secondsemester = Textbox.Text;

84. Explain what each line of the corrected code you got in question 83 above does.
The first line sets up the variable, and tells C# to set aside some memory that will hold a string of text.
The name of this storage area will be Secondsemester.
The second line is the one that actually stores something in the variable - the Text from a text box called
TextBox.

85. In the code you got in question 83 above, add a line of code that will display the output in a message box.
MessageBox.Show(Secondsemester);

86. Give a brief description of a class.


A class is can simply be described as a template that defines the form of an object. It specifies both the
data and the code that will operate on that data. Methods and variables that constitute a class are called
members of the class.

87. Briefly state the two (2) methods of adding classes in C# and their procedures.
Adding a C# Class Using Solution Explorer:
1. In Solution Explorer, right-click the project name and click Add, and then click Add Class.
The Add New Item dialog box appears with the C# Class icon already selected.
2. In the dialog box, enter a class name in the Name field and click Open. The new class is added to your
project.
Adding a C# Class Using Class View:
1. In Class View, right-click the project name and click Add
2. Then click Add Class
3. The C# Class Wizard appears

88. List at least five (5) folders that are created when one saves a work in C#.
1. Visual Studio 2005
2. Projects
3. ConsoleApplication1
4. bin
5. obj

89. What is the function of the double quotes and the semicolons in C#?
1. Double quotes: These tell C# that you want text.
2. Semicolons: All complete lines of code in C# must end with a semicolon. Miss one out and you'll get
error messages. Type the semicolon at the end and the red wiggly line will go away.

90. Cleary explain the term method in C# and write the syntax for creating one.
A method is a code block containing a series of statements. In C#, every executed instruction is done in
the context of a method.
Syntax:
attributes modifiers return-type method-name(parameters )
{
statements
}

91. Why are methods important?


Methods help you separate your code into modules that perform specific tasks. They are extremely useful
because they allow you to separate your logic into different units. You can pass information to methods,
have it perform one or more statements, and retrieve a return value. The capability to pass parameters
and return a value is optional and depends on what you want the method to do.

92. Explain the term method overloading and state its advantages.
Method overloading is a technique which allows the programmer to define many methods with the same
name but with a different set of parameters.
Advantages:
1. It provides improvement to code readability and maintainability.
2. It allows you to always call Math.Truncate.

93. Briefly explain any four (4) common variables in C#; stating their syntax.
String: String variables are always text. Click inside the two curly brackets of the button code, and add
the following:
string firstName;
Integer Variables: As well as storing text in memory you can, of course, store numbers. There are a
number of ways to store numbers, and the ones you'll learn about now are called Integer, Double and
Float. First up, though, are Integer variables. For example:
int myInteger;
Double and Float Variables: Integers, as was mentioned, are whole numbers. They can't store the point
something, like .7, .42, and .007. If you need to store numbers that are not whole numbers, you need a
different type of variable. You can use the double type, or the float type. You set these types of variables
up in exactly the same way: instead of using the word int, you type double, or float. Like this:
float myFloat;
double myDouble;
(Float is short for "floating point", and just means a number with a point something on the end.) The
difference between the two is in the size of the numbers that they can hold. For float, you can have up to
7 digits in your number. For doubles, you can have up to 16 digits. Float is a 32-bit number and double is
a 64-bit number.

94. How do you comment a line of code in C#?


Comments in C# are incorporated by adding slashes. For example:
protected override void Finalize()
{
try
{
// Destructor code
}
finally
{
base.Finalize();
}
}

95. With the aid of a well-labelled diagram, describe the Common Language Runtime (CLR) execution process.
Beyond just executing code, parts of the execution process directly affect your application design and
how a program behaves at runtime. Many of these subjects are handled throughout this book, but this
section highlights specific additional items you should know about. From the time you or another process
selects a .NET application for execution, the CLR executes a special process to run your application, shown
in the figure below:
96. Explain the term C# indexer and write the syntax for declaring a two-dimensional/multidimensional
indexer.
A C# indexer is a member that enables an object to be indexed in the same way as an array, a one-
dimensional indexer accepts a single value between the square brackets.
{
get {}
set {}
}

97. Define the term destructor and state its applications.


A destructor is a special member that can be added to a class. It is called automatically when an object is
no longer required and is being removed from memory. A destructor also known as a finalizer is a special
member that can be added to a class. It is executed automatically when the object is being removed from
memory.
Application of Destructors:
The destructor can be useful because it can ensure that all objects of a particular class terminate cleanly.
For example, if a class maintains a database connection, the destructor can be used to ensure that any
database transaction is rolled back if it has not been committed and that the database connection is closed
when the object is cleaned up.

98. Write a code that calls the finalizer of a base class object.
protected override void Finalize()
{
try
{
// Destructor code
}
finally
{
base.Finalize();
}
}

99. Explain the concept garbage collection, and state the key roles of garbage collector.
When objects are created they occupy some memory. As memory is a limited resource, it is important
that once the objects are no longer required, they are cleaned up and their memory is reclaimed. The
.NET framework uses a system of garbage collection to perform this activity automatically so that the
developer does not need to control this directly.
Role of the Garbage Collector:
1. The garbage collector periodically checks for objects in memory that are no longer in use and that are
referenced by no other objects.
2. It also detects groups of objects that reference each other but as a group have no other remaining
references. When detected, the objects' destructors are executed and the memory utilised is returned to
the pool of available memory.

100. What is the function of the static keyword in a C# declaration?


The 'static' keyword is used in the declaration to indicate the modified behaviour.

101. State the properties of static constructors.


1. A static constructor does not take access modifiers or have parameters.
2. A static constructor is called automatically to initialize the 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.
6. Static constructors are also useful when creating wrapper classes for unmanaged code, when the
constructor can call the LoadLibrary method.
7. If a static constructor throws an exception, the runtime will not invoke it a second time, and the type
will remain uninitialized for the lifetime of the application domain in which your program is running.

102. List three (3) types of static properties.


1. Read/write
2. Read-only
3. Write-only

103. Write a short note on the following:


(i) Solution explorer
Solution Explorer is a special window that enables you to manage solutions, projects, and files. It
provides a complete view of the files in a project, and it enables you to add or remove files and to
organize files into subfolders.
(ii) Precision
The number of digits that a variable can hold is known as precision. For float variable, C# is precise to 7
digits: anything more and the number is rounded off.

104. Specify the general form and composition of an instance variable.


The general form of a class definition that contains only instance variables and methods is given as:
class classname {
// declare instance variables
access type var1;
access type var2;
// ...
access type varN;
// declare methods
access ret-type method1(parameters) {
// body of method
}
access ret-type method2(parameters) {
// body of method
}
// ...
access ret-type methodN(parameters) {
// body of method
}
}

105. Compare and contrast default constructor and destructor.


A default constructor is simply the constructor that is applied in a class if no other constructor is
explicitly declared by the developer. This constructor causes all of the value type properties and
variables to be set to zero and all reference types to be set to null while a destructor is a special member
that can be added to a class. It is called automatically when an object is no longer required and is being
removed from memory.

106. With the aid of a simple code, explain the process of method calling.
Calling a method on an object is similar to accessing a field. After the object name; add a period, the
name of the method, and parentheses. Arguments are listed within the parentheses, and separated by
commas. The methods of the Motorcycle class can therefore be called like this:
Motorcycle moto = new Motorcycle();

moto.StartEngine();
moto.AddGas(15);
moto.Drive(5, 20);
107. With the aid of a diagram, discuss the concept of inheritance as related to the OOP.
Inheritance is a powerful object-oriented concept that permits the creation of hierarchical groups of
classes that share common functionality. Using inheritance, one class can be derived from another. The
derived class, also known as the child class or subclass, inherits functionality from the base class, also
known as the parent class or superclass. The subclass can add methods and properties or modify the
functionality that it has inherited to provide a more specialised version of the base class. Using
inheritance, classes become grouped together in a hierarchical tree structure. The more generalised
classes appear at the root of the hierarchy with the more specific classes appearing on the tree's
branches. This categorisation of classes into related types is why inheritance is sometimes referred to
as generalisation (or generalization). When using inheritance, all of the base class' methods, properties,
events, indexers, operators and some internal variables are all automatically provided to every subclass.
As this functionality is automatically available in the child class, there is no need to duplicate code. This
reduces maintenance problems, as changes need only to be made in one class, rather than throughout a
series of related classes.

108. Discuss what is meant by .NET?


Microsoft initially responded to the popularity of Java by producing a version of Java called Visual J++.
However, Microsoft decided on a more comprehensive response. Using many of the ground-breaking
concepts that Java implemented, Microsoft developed a language called C# that became the foundation
for the company's .NET platform. As with Java, C# relied heavily on the success and failures of earlier
languages. The .NET development environment includes many of the really good characteristics of
several other platforms. .NET incorporates many of concepts introduced by the initial Java release. The
.NET platform also builds upon many of the powerful features of the VB6 and Visual C++ environments.

109. With an illustrative example, explain the process of instantiating a class.


Although we have not explicitly added any functionality to the class, it can now be instantiated to create
objects. These objects will have the standard behaviour of all classes. To demonstrate this, return to the
program code file containing the Main method. In this method we will create a new vehicle object and
run its ToString method to see the results. As we have not yet defined how ToString should work, this
will simply show the fully qualified name.
static void Main(string[] args)
{
Vehicle car = new Vehicle();
Console.WriteLine(car.ToString()); // Outputs "ClassTest.Vehicle"
}
NB: The prefix of ClassTest is simply the name of the namespace of the Vehicle class.
110. With the aid of a simple code, explain the process of method declaration.
Methods are declared within a class or struct by specifying the access level, the return value, the name
of the method, and any method parameters. Method parameters are surrounded by parentheses, and
separated by commas. Empty parentheses indicate that the method requires no parameters. This class
contains three methods:
class Motorcycle
{
public void StartEngine() { }
public void AddGas(int gallons) { }
public int Drive(int miles, int speed) { return 0; }
}

You might also like