CIT351
CIT351
CIT351
GUIDE
CIT 351
C# PROGRAMMING
Course Developer/Writer Vivian Nwaocha
National Open University of Nigeria
Lagos
NATIONAL OPEN
UNIVERSITY OF NIGERIA
CIT 351 C# PROGRAMMING
Abuja Annex
245 Samuel Adesujo Ademulegun Street
Central Business District
Opposite Arewa Suites
Abuja
e-mail: @nou.edu.ng
URL: .nou.edu.ng
ISBN:
Printed by ……………..
For
National Open University of Nigeria
CIT 351 C#.Net Programming
Introduction……………………………………………….. 4
Brief overview of the Course…………………………....... 5
What you will learn in this Course ………………………..5
Course Aim………………………………………………... 5
Course Objectives…………………………………………. 5
Working through this Course……………………………… 7
Course Materials…………………………………………... 7
Study Units………………………………………………… 8
Recommended Texts………………………………………. 9
Assignment File…………………………………………… 11
Presentation Schedule……………………………………... 11
Assessment………………………………………………… 11
Tutor Marked Assignments (TMAs)………………………. 12
Final Examination and Grading…………………………… 12
Course Marking Scheme…………………………………… 13
Course Overview………………………………………….. 13
How to get the most from this course……………………. 15
Tutors and Tutorials……………………………………….. 17
Summary……….……………………………………………18
4
CIT 351 C#.Net Programming
Introduction
CIT 351: C# Programming is a 2 credit unit course for students studying towards
acquiring a Bachelor of Science in Computer Science and other related disciplines.
The course is divided into 4 modules and 15 study units. It will introduce students to
fundamental concepts of C# Programming, .NET framework and Visual Studio.NET.
This course also provides information on C# data types, syntax, expressions and C#
applications.
At the end of this course, it is expected that students should be able to understand, explain
and be adequately equipped with fundamental notions of C# Programming. The course
guide therefore gives you an overview of what the course; CIT 351 is all about, the
textbooks and other materials to be referenced, what you are expected to know in each
unit, and how to work through the course material. It suggests the general strategy to be
adopted and also emphasizes the need for self-assessment and tutor marked assignment.
There are also tutorial classes that are linked to this course and students are advised to
attend.
The overall aim of this course, CIT 351, is to introduce you to basic concepts of C#
programming in order to enable you create C# projects. This course provides hands-on,
case study examples, and reference materials designed to enhance your programming
skills. In the course of your studies, you will be equipped with definitions of common
terms, characteristics and applications of object-oriented programming using C#. You
will also learn about .NET framework and visualstudio.NET. Finally, you will learn
about C# expressions and operators.
5
CIT 351 C#.Net Programming
Course Aim
This course aims to introduce students to the basic concepts and features of C#
programming. It is hoped that the knowledge would enhance the programming expertise
of students to enable them develop C# based applications.
Course Objectives
It is important to note that each unit has specific objectives. Students should study them
carefully before proceeding to subsequent units. Therefore, it may be useful to refer to
these objectives in the course of your study of the unit to assess your progress. You
should always look at the unit objectives after completing a unit. In this way, you can be
sure that you have done what is required of you by the end of the unit.
However, below are overall objectives of this course. On completing this course, you
should be able to:
• Be able to use all the features of object oriented programming language effectively.
• Be able to design and develop a web based application package.
• Be able to develop a database management system that will interface the C#
programming language with database management system.
• Be able to implement simple algorithm in computer science processes
To complete this course, you are required to study all the units, the recommended text
books, and other relevant materials. Each unit contains some self-assessment exercises
and tutor marked assignments, and at some point in this course, you are required to
submit the tutor marked assignments. There is also a final examination at the end of this
course. Stated below are the components of this course and what you have to do.
7
CIT 351 C#.Net Programming
Course Materials
Study Units
There are 15 study units and 5 modules in this course. They are:
8
CIT 351 C#.Net Programming
Recommended Texts
470
17. Perkins, B., Hammer, J. V., & Reid, J. D. (2018). Beginning C# 7 Programming
with Visual Studio® 2017. In Beginning C# 7 Programming with Visual Studio®
2017.
18. Pierce, Benjamin (2002). Types and Programming Languages. MIT Press.
19. Rumbaugh, James; Michael Blaha, William Premerlani, Frederick Eddy, William
Lorensen (1991). Object-Oriented Modeling and Design. Prentice Hall.
20. Schreiner, A. (1993). Object oriented programming with ANSI-C.
21. Studio, V. (2013). Fundamentals of Computer Programming with C# (The Bulgarian
C# Programming Book) by Svetlin Nakov & Co. http://www.introprogramming.info.
Assignment File
The assignment file will be given to you in due course. In this file, you will find all the
details of the work you must submit to your tutor for marking. The marks you obtain for
these assignments will count towards the final mark for the course. Altogether, there are
15 tutor marked assignments for this course.
Presentation Schedule
The presentation schedule included in this course guide provides you with important
dates for completion of each tutor marked assignment. You should therefore endeavour to
meet the deadlines.
Assessment
There are two aspects to the assessment of this course. First, there are tutor marked
assignments; and second, the written examination. Therefore, you are expected to take
note of the facts, information and problem solving gathered during the course. The tutor
marked assignments must be submitted to your tutor for formal assessment, in
accordance to the deadline given. The work submitted will count for 40% of your total
course mark. At the end of the course, you will need to sit for a final written
examination. This examination will account for 60% of your total score.
10
CIT 351 C#.Net Programming
There are 15 TMAs in this course. You need to submit all the TMAs. The best 4 will
therefore be counted. When you have completed each assignment, send them to your
tutor as soon as possible and make certain that it gets to your tutor on or before the
stipulated deadline. If for any reason you cannot complete your assignment on time,
contact your tutor before the assignment is due to discuss the possibility of extension.
Extension will not be granted after the deadline, unless on extraordinary cases.
The final examination for CIT 351 will be of last for a period of 2 hours and have a value
of 60% of the total course grade. The examination will consist of questions which reflect
the self assessment exercise and tutor marked assignments that you have previously
encountered. Furthermore, all areas of the course will be examined. It would be better to
use the time between finishing the last unit and sitting for the examination, to revise the
entire course. You might find it useful to review your TMAs and comment on them
before the examination. The final examination covers information from all parts of the
course.
Assessment Marks
Assignment 1 – 15 15 assignments, 40% for the best 4
Total = 10% X 4 = 40%
Final Examination 60% of overall course marks
Total 100% of Course Marks
Course Overview
This table indicates the units, the number of weeks required to complete them and the
assignments.
11
CIT 351 C#.Net Programming
12
CIT 351 C#.Net Programming
In distance learning, the study units replace the university lecturer. This is one of the
huge advantages of distance learning mode; you can read and work through specially
designed study materials at your own pace and at a time and place that is most
convenient. Think of it as reading from the teacher, the study guide indicates what you
ought to study, how to study it and the relevant texts to consult. You are provided with
exercises at appropriate points, just as a lecturer might give you an in-class exercise.
Each of the study units follows a common format. The first item is an introduction to the
subject matter of the unit and how a particular unit is integrated with the other units and
the course as a whole. Next to this is a set of learning objectives. These learning
objectives are meant to guide your studies. The moment a unit is finished, you must go
back and check whether you have achieved the objectives. If this is made a habit, then
you will increase your chances of passing the course. The main body of the units also
guides you through the required readings from other sources. This will usually be either
from a set book or from other sources. Self assessment exercises are provided throughout
the unit, to aid personal studies and answers are provided at the end of the unit. Working
through these self tests will help you to achieve the objectives of the unit and also prepare
you for tutor marked assignments and examinations. You should attempt each self test as
you encounter them in the units.
The following are practical strategies for working through this course
There are 8 hours of tutorial provided in support of this course. You will be notified of
the dates, time and location together with the name and phone number of your tutor as
soon as you are allocated a tutorial group. Your tutor will mark and comment on your
assignments, keep a close watch on your progress and on any difficulties you might
encounter and provide assistance to you during the course.
You must mail your tutor marked assignment to your tutor well before the due date. At
least two working days are required for this purpose. They will be marked by your tutor
and returned to you as soon as possible. Do not hesitate to contact your tutor by
telephone, e-mail or discussion board if you need help. The following might be
circumstances in which you would find help necessary: contact your tutor if:
• You do not understand any part of the study units or the assigned readings.
• You have difficulty with the self test or exercise.
• You have questions or problems with an assignment, with your tutor‘s comments on an
14
CIT 351 C#.Net Programming
You should endeavour to attend the tutorials. This is the only opportunity to have face-to-
face contact with your tutor and ask questions which are answered instantly. You can
raise any problem encountered in the course of your study. To gain the maximum benefit
from the course tutorials, have some questions handy before attending them. You will
learn a lot from participating actively in discussions. GOODLUCK!
15
CIT 351 C#.Net Programming
MAIN COURSE
Abuja Annex
245 Samuel Adesujo Ademulegun Street
Central Business District
Opposite Arewa Suites
Abuja
e-mail: @nou.edu.ng
URL: .nou.edu.ng
16
CIT 351 C#.Net Programming
17
CIT 351 C#.Net Programming
UNIT 1 INTRODUCTION TO C#
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 What is C#?
3.2 Origin of C#
3.3 Advancements in C#
3.3.1 C# Versions
3.4 Language Name
3.5 C# Features
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
You are welcome to the world of C# programming language. This unit gives you a basic
idea about C#. However there will be no difficulty in learning this language if you are a
fresher, because this unit will elucidate the basic concepts and features of C# right from
the beginning.
Even if you have gained previous programming experience with any conventional
programming language, it is recommended that you go through the entire unit
systematically to gain some insight of the course.
2.0 OBJECTIVES
C# is one of the most popular programming languages designed for the Common
Language Infrastructure used by millions of developers worldwide. It supports all
features of an Object Oriented language such as abstraction, encapsulation, inheritance,
and polymorphism features. It is fully interoperable with other .NET languages such as
VB.NET, Eiffel.NET or Oberon.NET and executed in a special environment called the
Common Language Runtime (CLR), a part of the platform .Net Framework that
contains bundles of standard libraries providing basic functionality, compilers, debuggers
and other development tools.
3.2 Origin
Microsoft, with Anders Hejlsberg as Chief Engineer, created C# as part of their .NET
initiative and subsequently opened its specification in 2002 via the ECMA (Ecma-334).
Thus, the language is open to implementation by other parties. Other implementations
include Mono and DotGNU. Microsoft's original plan was to create a rival to Java,
named J++ but this was abandoned to create C#, codenamed "Cool". Microsoft submitted
19
CIT 351 C#.Net Programming
3.3 Advancements in C#
During the development of .NET Framework, the class libraries were originally written
in a language/compiler called Simple Managed C (SMC). In January 1999, Anders
Hejlsberg formed a team to build a new language at the time called Cool, which stood
for "C like Object Oriented Language". Microsoft had considered keeping the name
"Cool" as the final name of the language, but chose not to do so for trademark reasons.
By the time the .NET project was publicly announced at the July 2000 Professional
Developers Conference, the language had been renamed C#, and the class libraries and
ASP.NET runtime had been ported to C#.
C#'s principal designer and lead architect at Microsoft is Anders Hejlsberg, who was
previously involved with the design of Turbo Pascal, CodeGear Delphi (formerly
Borland Delphi), and Visual J++. In interviews and technical papers he has stated that
flaws in most major programming languages (e.g. C++, Java, Delphi, and Smalltalk)
drove the fundamentals of the Common Language Runtime (CLR), which, in turn,
drove the design of the C# programming language itself.
3.3.1 C# Versions
In the course of its development, C# has gone through several versions:
C# 1.0 - introduced 2000 / released January 2002
C# 1.1 - released April 2003
C# 2.0 - released November 2005
C# 3.0 - released November 2007
C# 4.0 - in development
C# 4.0 – released April 2010
C# 5.0 – released August 2012
C# 6.0 – released July 2015
C# 7.0 – released March 2017
C# 7.1 – released August 2017
C# 7.2 – released November 2017
C# 7.3 – released May 2018
C# 8.0 – released September 2019
20
CIT 351 C#.Net Programming
The name C#, pronounced as "C sharp", was inspired from musical notation where a
sharp indicates that the written note should be made a half-step higher in pitch. This is
similar to the language name of C++, where "++" indicates that a variable should be
incremented by 1. The sharp symbol also resembles a ligature of four "+" symbols (in a
two-by-two grid), further implying that the language is an increment of C++.
Due to technical limitations of display (fonts, browsers, etc.) and the fact that the sharp
symbol (♯ , U+266F, MUSIC SHARP SIGN) is not present on the standard keyboard,
the number sign (#, U+0023, NUMBER SIGN) was chosen to represent the sharp
symbol in the written name of the programming language. This convention is reflected in
the ECMA-334 C# Language Specification. However, when it is practical to do so (for
example, in advertising or in box art), Microsoft uses the intended musical symbol.
3.5 C# Features
• There are no global variables or functions. All methods and members must be declared
within classes. Static members of public classes can substitute for global variables and
functions.
C# supports strongly type implicit variable declarations with the keyword (var), and
implicitly typed arrays with the keyword (new[]) followed by a collection initializer
• Local variables cannot shadow variables of the enclosing block, unlike C and C++.
Variable shadowing is often considered confusing by C++ texts.
• C# supports a strict Boolean datatype, bool. Statements that take conditions, such as
while and if, require an expression of a boolean type. While C++ also has a boolean type,
it can be freely converted to and from integers, and expressions such as if(a) require only
that a is convertible to bool, allowing a to be an int, or a pointer. C# disallows this
"integer meaning true or false" approach on the grounds that forcing programmers to use
expressions that return exactly bool can prevent certain types of programming mistakes
such as if (a = b) (use of = instead of ==).
• In C#, memory address pointers can only be used within blocks specifically marked as
unsafe, and programs with unsafe code need appropriate permissions to run. Most object
access is done through safe object references, which always either point to a "live" object
or have the well-defined null value; it is impossible to obtain a reference to a "dead"
object (one which has been garbage collected), or to a random block of memory. An
21
CIT 351 C#.Net Programming
4.0 CONCLUSION
In this unit, we defined some basic concepts of C#. We also looked at the advancements
in C# as well as the language name.
5.0 SUMMARY
We hope you enjoyed this unit. This unit provided an overview of C#: basic definition,
features, versions and language name. Now, let us attempt the questions below.
22
CIT 351 C#.Net Programming
23
CIT 351 C#.Net Programming
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 ECMA International Standards
3.2 Aims of ECMA
3.2.1 What ECMA specifies
3.2.2 What ECMA does not specify
3.3 Design Goals
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
In unit 1, we gave an overview of ‗C# programming‘ as well as its basic features. This
unit provides information about the ECMA international standards.
2.0 OBJECTIVES
This International Standard specifies the form and establishes the interpretation of
programs written in the C# programming language.
ECMA specifies:
25
CIT 351 C#.Net Programming
26
CIT 351 C#.Net Programming
4.0 CONCLUSION
From our studies in this unit, it is vital to remember that the ECMA International
Standard specifies the form and establishes the interpretation of programs written in the
C# programming language. It is equally worth noting that ECMA has some specific
design goals.
5.0 SUMMARY
In this unit, we looked at the ECMA international standards, its‘ aims; what it specifies
and what it does not specify as well as it‘s design goals. We hope you found the unit
enlightening. To assess your comprehension, attempt the questions below.
C#".
14. Simon, Raphael; Stapf, Emmanuel; Meyer, Bertrand (June 2002). "Full Eiffel on the
.NET Framework".
15. "The ECMA C# and CLI Standards". 2009 -07-06.
16. Zander, Jason (November 23, 2007). "Couple of Historical Facts".
28
CIT 351 C#.Net Programming
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 C# Platform
3.2 Relationship between C# and .NET Framework
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
The initial task we have in this unit is to identify the target platform of C#, so that you
can see the relationship between C# and .NET framework. You might be tempted to think
you're never going to get to grips with this. But don't worry - after a few lessons, things
will start to feel familiar, and you will gain more confidence.
2.0 OBJECTIVES
By the end of this unit, you'll have learnt about the following:
• The target platform of C#
• The relationship between C# and .NET framework
3.1 C# Platform
In brief, C# (unlike C++, PERL, COBOL, Pascal, etc.) is a language that targets one and
only one platform. This platform is the .NET Framework. However, the .NET
Framework itself is a computing platform that is designed to be hosted by any operating
system. It is the most common version of the .Net Framework. At the time of this writing,
the .Net runs primarily on Microsoft Windows which led to a family of .NET platforms
targeting mobile computing, embedded devices, rich internet applications, alternative
29
CIT 351 C#.Net Programming
operating systems, and web-browser plug-ins and I know of two other major operating
systems for which a version of the .NET Framework is being developed. So you can see
that although C# is designed to target only the Framework, the Framework itself is
flexible enough to run your C# programs on many types of systems.
The relationship between C# and the .NET Framework is somewhat unique. In a way it
is similar to the relationship between Java and the Java Virtual Machine, however there
are several major differences. First, C# is not the only language that can be used to write
.NET Framework applications (called Managed Applications). Second, .NET or
managed applications run in native machine-language and are not interpreted. Third, C#
or managed applications do not run in a sandbox. Fourth, .NET has a Common Language
Runtime (CLR) which is a virtual component of .NET framework. Fifth, C# is a part of
.NET that has different features like Boolean Conditions. Standard Library, Indexers,
Conditional Compilation, etc. Sixth, the basic usage of C# is essentially concentrated on
desktop-based applications and in the case of .NET, it is used to develop Microsoft based
applications.
What you should take away from this unit, as a programmer learning C#, is that C# is a
programming language (that you will find simple to master); however, much of what you
can do with C# is really more a part of the .NET Framework itself.
4.0 CONCLUSION
C# is a language that targets only one platform. This platform is the .NET Framework.
C# is not the only language that can be used to write .NET Framework applications
(called Managed Applications). The .NET or managed applications run in native
machine-language and are not interpreted. C# or managed applications do not run in a
sandbox. .
NET has a Common Language Runtime (CLR) which is a virtual component of .NET
framework. C# is a part of .NET that has different features like Boolean Conditions.
Standard Library, Indexers, Conditional Compilation, etc. The basic usage of C# is
30
CIT 351 C#.Net Programming
5.0 SUMMARY
In this unit, we considered the .NET framework which is the platform for C#. Hoping
that you understood the topics discussed, you may now attempt the questions below.
Outline 2 key differences between C# and .NET framework Give a brief description of
the .NET framework
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 What is .Net?
3.2 Starting a New Program in C#
3.3 Console Applications
3.4 Basic C#.Net Syntax
3.5 C#.Net Comments
3.6 Structure of a Console Application
4.0 Conclusion
5.0 Summary
6.0 Tutored Marked Assignments
7.0 References for further reading
1.0 INTRODUCTION
2.0 OBJECTIVES
32
CIT 351 C#.Net Programming
Other applications include code that runs in the cloud via Windows Azure, and
iOS, Android, and Windows Phone support with the Xamarin platform.
Creating a Project
When you select new project you are presented with a screen in Figure 1..
33
CIT 351 C#.Net Programming
The type of project that you will select from the pane on the left is Visual C# Projects
(unless you don‘t want to create a C# project). Then you will build your project from a
template by scrolling down by the right.
Once you have created a C# project to work with in VS.NET you can do
your regular programming tasks. This includes editing source code
files, compiling, and debugging.
34
CIT 351 C#.Net Programming
The solution explorer (see Figure 2) is your command central for dealing
with solution (which is what contains one or more related projects). In
Figure2 the Solution Explorer shows a solution named LearningC# which
contains four projects.
From the Solution Explorer you can bring up source modules. Add source
modules to a project. Debug a project or add and remover projects from a
solution. The general rule is that you right-click your mouse on the item you
want to affect, and then select the action from the menu that pops up.
• Console applications are those that don‘t make use of the graphical windows
environment. Instead, you run the application in a command prompt
window, and interact with it in a much simpler way.
36
CIT 351 C#.Net Programming
console.WriteLine(―C# Programming!‖);
CONSOLE.WRITELINE(―C# Programming!‖);
37
CIT 351 C#.Net Programming
Console.Writeline(―C# Programming!‖);
38
CIT 351 C#.Net Programming
4.0 CONCLUSION
In this unit, we start a new project and demonstrated the use of comments. We also
looked at the achievable tasks in C#.Net as well as Console application development.
5.0 SUMMARY
We hope you enjoyed this unit. This unit provided an overview of C#: basic definition,
features, versions and language name. Now, let us attempt the questions below.
39
CIT 351 C#.Net Programming
40
CIT 351 C#.Net Programming
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Variables and Expressions
3.2 Variable Naming
3.3 Variable Declaration
3.4 Simple Data Types and allowed values
3.5 Variable declaration and assignment
3.6 Expression
4.0 Conclusion
5.0 Summary
6.0 Tutored Marked Assignments
7.0 References for further reading
1.0 Introduction
The initial task we have in this unit is to known the need for variable declaration, data
types and expression in C#. and use that to create a new project in Console application
environment.
2.0 Objectives
C# syntax for declaring variables merely specifies the type and variable name:
< type > < name > ;
int a; // to hold whole number
double variableName;
double VariableName;
float sum;
string firstname
42
CIT 351 C#.Net Programming
• Recall that you declare variables simply using their type and name:
int age;
• You then assign values to variables using the ―=‗ assignment operator:
43
CIT 351 C#.Net Programming
age = 25;
int age, height; //Here, age and height are both declared as
integer types.
int age = 25
double length = 4.5, weight = 2.5;
decimal breadth = 7.58m; // declared as literal value of decimal
string myString;
myString = ― hello world‖
3.6 Expression
Now that you‘ve learned how to declare and initialize variables, it‘s time to look at
manipulating them. C# contains a number of operators for this purpose, including the =
assignment operator.
44
CIT 351 C#.Net Programming
By combining operators with variables and literal values (together referred to as operands
when used with operators), you can create expressions, which are the basic building
blocks of computation.
4.0 CONCLUSION
In this unit, we defined some basic concepts of C#. We also looked at the advancements
in C# as well as the language name.
5.0 SUMMARY
We hope you enjoyed this unit. This unit provided an overview of C#: basic definition,
features, versions and language name. Now, let us attempt the questions below.
14. Simon, Raphael; Stapf, Emmanuel; Meyer, Bertrand (June 2002). "Full Eiffel on the
.NET Framework".
15. "The ECMA C# and CLI Standards". 2009 -07-06.
16. Zander, Jason (November 23, 2007). "Couple of Historical Facts".
46
CIT 351 C#.Net Programming
CONTENT
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Operators Categories
3.2 Mathematical Operators
3.3 Assignment Operators
3.4 Binary Operators for string concatenation
3.5 Incremental Operators
3.6 Assessment Exercises
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings
1.0 Introduction
2.0 Objectives
47
CIT 351 C#.Net Programming
48
CIT 351 C#.Net Programming
• The binary + operator does make sense when used with string type variables.
string var1,var2,var3;
var1 = var2 + var3; /* string var2 and var3 are concatenated
49
CIT 351 C#.Net Programming
50
CIT 351 C#.Net Programming
51
CIT 351 C#.Net Programming
52
CIT 351 C#.Net Programming
• Create a new console application called Practical1 and save in a folder called
Practical under the default VS directory that perform the following operations:
• Ask for your firstname and surname
• Concatenate the two names for username
• Ask for your year of birth and the present year to determine your age.
• Print a welcome message with the username and age.
• Prompt to enter two numbers successively to calculate
– (i) X+Y, (ii) X-Y, (iii) X/Y and (iv) X%Y
• Print out the output for each expression on different lines
E.g ― sum of X and Y is ---‖
53
CIT 351 C#.Net Programming
Note: Even if you don’t have a laptop, write down the solution
Solution Screenshot
4.0 CONCLUSION
In this unit, we defined some basic concepts of C#. We also looked at the advancements
in C# as well as the language name.
5.0 SUMMARY
We hope you enjoyed this unit. This unit provided an overview of C#: basic definition,
features, versions and language name. Now, let us attempt the questions below.
UNIT QUIZ
❑ myVariableIsGood
❑ 99Flake
❑ floor
❑ time2GetJiggyWidIt
❑ wrox.com
Write a console application that obtains four int values from the user and displays the
product.
Computerworld.
6. Horton, Anson (2006-09-11). "C# XML documentation comments FAQ".
7. Kovacs, James (September 07, 2007). "C#/.NET History Lesson".
8. Microsoft. September 4, 2003."Visual C#.net Standard" (JPEG).
9. Microsoft (June 18, 2009) C# Language Reference.
10. O' Reilly. (2002).C# Language Pocket Reference. ISBN 0-596-00429-X.
11. Petzold, Charles (2002). Programming Microsoft Windows with C#. Microsoft Press.
ISBN 0-7356-1370-2.
12. Steinman, Justin (November 7, 2006). "Novell Answers Questions from the
Community".
13. Stallman, Richard (June 26, 2009). "Why free software shouldn't depend on Mono or
C#".
14. Simon, Raphael; Stapf, Emmanuel; Meyer, Bertrand (June 2002). "Full Eiffel on the
.NET Framework".
15. "The ECMA C# and CLI Standards". 2009 -07-06.
16. Zander, Jason (November 23, 2007). "Couple of Historical Facts".
55
CIT 351 C#.Net Programming
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Goto statement
3.2 Branching
3.3 The If Statement
3.4 The If-else statement
3.5 The Switch statement
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings
1.0 Introduction
The initial task we have in this unit is to know the various flow controls in C#.
2.0 Objectives
• C# enables you to label lines of code and then jump straight to them using the goto
statement.
• The goto statement is used as follows:
goto < labelName > ;
• Labels are defined as follows:
< labelName > :
Program Sample
56
CIT 351 C#.Net Programming
int myInteger = 5;
goto myLabel;
myInteger += 10; // this line of code will never be executed
myLabel:
Console.WriteLine(―myInteger = {0}‖, myInteger);
57
CIT 351 C#.Net Programming
3.2 Branching:
The ternary or conditional operator
The if statement
The switch statement
58
CIT 351 C#.Net Programming
59
CIT 351 C#.Net Programming
this:
if (var1 < var2)
comparison = ―less than‖;
if (var1 == var2)
comparison = ―equal to‖;
if (var1 > var2)
comparison = ―greater than‖;
61
CIT 351 C#.Net Programming
Explanation
• The value in < testVar > is compared to each of the < comparisonValX >
values (specified with case statements), and if there is a match, then the code
supplied for this match is executed.
• If there is no match, then the code in the default section is executed if this
block exists.
• On completion of the code in each section, you have an additional
command, break .
• With the break command, it is illegal for the flow of execution to reach a
62
CIT 351 C#.Net Programming
Class Exercise
1. Sunny Sunglasses
2. Rain Umbrella
3. Cold Jacket
4 Others Jacket
Solution program
{
Console.WriteLine ("Enter the current weather: rain, sunny ,cold, blast or
hot");
string currentWeather = Console.ReadLine();
string equipment;
switch (currentWeather) // this line will be sensitive to the
cases
{
case "sunny":
equipment = "sunglasses";
break;
case "rain":
equipment = "umbrella";
break;
case "cold":
63
CIT 351 C#.Net Programming
default:
equipment = "jacket";
break;
}
Tutor Assessment
• Write a console application that will accept the students score in a course
and print the letter grade as follows:
– 70 and above: A
– 60-69 B
– 50-59 C
– 45-49 D
– Below 45 F
65
CIT 351 C#.Net Programming
4.0 CONCLUSION
In this unit, we defined some basic concepts of C#. We also looked at the advancements
in C# as well as the language name.
5.0 SUMMARY
We hope you enjoyed this unit. This unit provided an overview of C#: basic definition,
features, versions and language name. Now, let us attempt the questions below.
What is the different between the If statement and the Switch statement?.
UNIT QUIZ
❑ myVariableIsGood
❑ 99Flake
❑ floor
❑ time2GetJiggyWidIt
❑ wrox.com
Write a console application that obtains four int values from the user and displays the
product.
67
CIT 351 C#.Net Programming
CONTENT
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 What is Program control?
3.2 C# Looping Methods
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
Program control is how a program makes decisions or organizes its activities. Program
control typically involves executing particular code based on the outcome of a prior
operation or a user input.
2.0 OBJECTIVES
68
CIT 351 C#.Net Programming
Write short note on simple sequence, selection and iteration control structure.
Do loop
The structure of a do loop is as follows, where < Test > evaluates to a Boolean value:
do
{
< code to be looped >
} while ( < Test > );
The semicolon after the while statement is required.
Example
For example, you could use the following to write the numbers from 1 to 10 in a
column:
static void Main()
{
int i = 1;
do
{
Console.WriteLine("{0}", i++);
}while (i<=10);
}
69
CIT 351 C#.Net Programming
70
CIT 351 C#.Net Programming
while Loops
while loops are very similar to do loops, but they have one important difference:
The Boolean test in a while loop takes place at the start of the loop cycle, not the end.
If the test evaluates to false, then the loop cycle is never executed.
Instead, program execution jumps straight to the code following the loop.
The Syntax
while ( < Test > )
{
< code to be looped >
}
for Loops
for loop executes a set number of times and maintains its own counter.
To define a for loop you need the following information:
A starting value to initialize the counter variable .
A condition for continuing the loop, involving the counter variable .
An operation to perform on the counter variable at the end of each loop cycle
71
CIT 351 C#.Net Programming
This information must be placed into the structure of a for loop as follows:
for ( < initialization > ; < condition > ; < operation > )
{
< code to loop >
}
Interrupting Loops
Continue
Continue only stops the current cycle, not the whole loop, as shown here:
int i;
for (i = 1; i < = 10; i++)
{
if ((i % 2) == 0)
continue;
Console.WriteLine(i);
}
72
CIT 351 C#.Net Programming
Goto
The third method of interrupting a loop is to use goto , as shown earlier:
int i = 1;
while (i < = 10)
{
if (i == 6)
goto exitPoint;
Console.WriteLine(―{0}‖, i++);
}
Console.WriteLine(―This code will never be reached.‖);
exitPoint:
Console.WriteLine(―This code is run when the loop is exited using goto.‖);
4.0 CONCLUSION
In this unit, we defined some basic concepts of C#. We also looked at the advancements
in C# as well as the language name.
5.0 SUMMARY
We hope you enjoyed this unit. This unit provided an overview of looping and iteration.
Now, let us attempt the questions below.
What is the different between the If statement and the Switch statement?.
UNIT QUIZ
❑ myVariableIsGood
❑ 99Flake
❑ floor
❑ time2GetJiggyWidIt
❑ wrox.com
73
CIT 351 C#.Net Programming
Write a console application that obtains four int values from the user and displays the
product.
74
CIT 351 C#.Net Programming
CONTENT
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Type conversion
3.2 The Implicit type conversion
3.3 The Explicit type conversion
3.4 Complex Variable Types
3.5 Errors and Exception Handling in C#
4.0 Conclusion
50 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
Program control is how a program makes decisions or organizes its activities. Program
control typically involves executing particular code based on the outcome of a prior
operation or a user input.
2.0 OBJECTIVES
Explicit conversion
ushort destinationVar;
char sourceVar = ‗a‘;
destinationVar = sourceVar;
Console.WriteLine(―sourceVar val: {0}‖, sourceVar);
Console.WriteLine(―destinationVar val: {0}‖, destinationVar);
Example of running program
76
CIT 351 C#.Net Programming
77
CIT 351 C#.Net Programming
You can explicitly ask the compiler to convert a value from one data type to
another if they are compatible and when precision will not be lost.
byte destinationVar;
short sourceVar = 7;
destinationVar = sourceVar;
Console.WriteLine(―sourceVar val: {0}‖, sourceVar);
Console.WriteLine(―destinationVar val: {0}‖, destinationVar);
78
CIT 351 C#.Net Programming
value3 ,
...
valueN
}
• you can declare variables of this new type as follows:
typeName varName ;
• You can assign values using the following:
varName = typeName.value ;
• Enumerations have an underlying type used for storage.
Each of the values that an enumeration type can take is stored as a value of
this underlying type, which by default is int .
You can specify a different underlying type by adding the type to the enumeration
declaration:
enum typeName : underlyingType
{
value1 ,
value2 ,
value3 ,
...
valueN
}
Enumerations can have underlying types of byte , sbyte , short , ushort , int , uint ,
long , and ulong .
80
CIT 351 C#.Net Programming
could not be successfully completed. The method causing the operation could
catch the exception (and handle the error) or pass the exception through to the
calling method.
82
CIT 351 C#.Net Programming
4.0 CONCLUSION
We discovered that The CSharp type system contains three Types, they are: Value Types,
Reference Types and Pointer Types. We equally saw that the key difference between
value types and reference types is the mode of storing values in memory.
5.0 SUMMARY
In this unit, we learnt about the general notion of type and the C# type system in
particular. OK! Let us attempt the questions below.
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Array and Multi-dimensional Array
3.2 Declaring and using Array in C# program
3.2.2 Using one and multi-dimensional array
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
Array provides structured ways of storing data values. In this unit, concept of Array is
demystified. Different types of Array is also illustrated..
1.0 OBJECTIVES
Sometimes you want to store several values of the same type at the same time,
without having to use a different variable for each value.
Example
string friendName1 = ―Robert Barwell‖;
84
CIT 351 C#.Net Programming
Arrays are indexed lists of variables stored in a single array type variable.
For example, you might have an array called friendNames that stores the three names
shown in previous slide.
You can access individual members of this array by specifying their index in square
brackets, as
friendNames[ < index > ]
This index is simply an integer, starting with 0 for the first entry, using 1 for the second,
and so on.
This means that you can go through the entries using a loop:
int i;
for (i = 0; i < 3; i++)
{
Console.WriteLine(―Name with index of {0}: {1}‖, i, friendNames[i]);
}
85
CIT 351 C#.Net Programming
Specifying an array using literal values simply involves providing a comma - separated
list of element values enclosed in curly braces:
int[] myIntArray = {5, 9, 10, 2, 99};
86
CIT 351 C#.Net Programming
Here, myIntArray has five elements, each with an assigned integer value
Here, you use the new keyword to explicitly initialize the array, and a constant value to
define the size.
This method results in all the array members being assigned a default value, which is 0
for numeric types.
Class Exercise
Write a program in C# Sharp to calculate the sum of elements in an array. For example, if
you enter 5,7,3,2,9 the program should display
The sum of the elements of the array is 26
Alternatively, you can use literal values for initial assignment. Here, you use nested
blocks of curly braces, separated by commas:
This array has the same dimensions as the previous one — that is, three rows and four
columns.
hillHeight[2,1]
You can then manipulate this element just as you can other elements.
This expression will access the second element of the third nested array as defined
previously (the value will be 4).
Class Work
Write a program to read in the following array and display it again looking exactly like
this.
1 2 3 4
5 6 7 8
9 10 11 12
A sample code for searching an array using linear search algorithm is shown below:
88
CIT 351 C#.Net Programming
The selection sort algorithm is based on the idea of selecting the largest array element
and swapping it with the last array element. The result is an unsorted list whose size is 1
less than the size of the original list, which is followed by a sorted list of size 1
(remember that a single value is a sorted list of size 1.) If we do this step again on the
unsorted list, we will have an ordered list of size 2 at the end, and the size of the
unordered list will be reduced by 1. Repetitive application of this process will give us a
sorted list when the size of the unsorted list becomes one. This technique is known as
simple selection sort. Presented in the following codes:
Assignment
Write and implement a C#.net program to arrange the ages of ten students in a class in
ascending order of youngest to the oldest in the class.
4.0 CONCLUSION
5.0 SUMMARY In summary, this unit looked an essential concept of C# array and
different types. We can now attempt the questions below.
89
CIT 351 C#.Net Programming
90
CIT 351 C#.Net Programming
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 String Manipulation
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
To start with, note that a string type variable can be treated as a read - only array of char
variables.
This means that you can access individual characters using syntax like the following:
string myString = ―A string‖;
char myChar = myString[1];
• You can‘t assign individual characters in this way.
91
CIT 351 C#.Net Programming
• To get a char array that you can write to, you can use the following code.
• This uses the ToCharArray() command of the array variable:
string myString = ―A string‖;
char[] myChars = myString.ToCharArray();
As with arrays, you can also get the number of elements using myString.Length .
This gives you the number of characters in the string:
string myString = Console.ReadLine();
Console.WriteLine(―You typed {0} characters.‖, myString.Length);
string userResponse = Console.ReadLine();
userResponse = userResponse.Trim();
if (userResponse.ToLower() == ―yes‖)
{
// Act on response.
}
Another example
char[] trimChars = {‗ ‗, ‗e‘, ‗s‘};
string userResponse = Console.ReadLine();
userResponse = userResponse.ToLower();
userResponse = userResponse.Trim(trimChars);
if (userResponse == ―y‖)
{
// Act on response.
}
Write a string processing program in C# to search for the length of surname of a student
named: Jonathan DANIEL, assuming DANIEL is the surname.
4.0 CONCLUSION
In conclusion, CSharp is a strongly typed language, therefore every variable and object
must have a declared type. The following are the commonly used datatypes in C#: bool,
int, decimal and string.
5.0 SUMMARY
In this unit, we discovered what data types portray and identified how to declare a
variable in C#. We equally considered the common data types in C# and gave specific
92
CIT 351 C#.Net Programming
examples of each data type in C# Hope you grasped the key points. Now, let us attempt
the questions below.
93
CIT 351 C#.Net Programming
UNIT 3: FUNCTIONS
CONTENT
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 What is a function
3.2 Advantages of function
3.3 Defining and using function
3.4 Rules for naming a function
3.5 Return value and local variables
3.6 Invoking a function and parameter passing
3.7 Program examples and class exercise
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings
1.0 Introduction
2.0 Objectives
3.1 Function
Functions help to solve a certain problem and eventually take parameters and return a
result. For example, if you have a function that calculates the maximum value in an
array, you can use this function from any point in your code, and use the same lines of
code in each case. This concept is referred to as reusability.
Functions help to solve a certain problem and eventually take parameters and return a
result.
94
CIT 351 C#.Net Programming
For example, if you have a function that calculates the maximum value in an array, you
can use this function from any point in your code, and use the same lines of code in each
case.
Functions make your code more readable, as you can use them to group related code
together, thereby reducing the length of your code.
Functions can also be used to create multipurpose code, enabling them to perform the
same operations on varying data.
For example, you could supply an array to search as a parameter and obtain the maximum
value in the array as a return value. This means that you can use the same function to
work with a different array each time.
Reusability - supply code once.
95
CIT 351 C#.Net Programming
Local Variables
Return Values
The simplest way to exchange data with a function is to use a return value.
Functions that have return values evaluate to that value, in exactly the same way that
variables evaluate to the values they contain when you use them in expressions.
Just like variables, return values have a type. When a function returns a value, you have
to modify your function in two ways: Specify the type of the return value in the function
declaration instead of using the void keyword.
Use the return keyword to end the function execution and transfer the return value to the
calling code.
Invoking or calling a method is actually the process of execution of the method‘s code,
placed into its body.
To invoke a method, write the method‘s name <method_name>, followed by the round
brackets and semicolon ";" at the end: <method_name>();
When a function is to accept parameters, you must specify the following:
A list of the parameters accepted by the function in its definition, along with the types of
those parameters .
A matching list of parameters in each function call .
This involves the following code, where you can have any number of parameters, each
with a type and a name:
static < returnType > < functionName > ( < paramType > < paramName > , ...)
{
...
return < returnValue > ;
}
The parameters are separated using commas, and each of these parameters is accessible
96
CIT 351 C#.Net Programming
Imagine we are in a bookstore and we want to calculate the amount of money we must
pay for all the books we bought.
We will create a method that gets the prices of all the books as an array of type decimal[],
and then returns the total amount we must pay:
97
CIT 351 C#.Net Programming
The simplest way to exchange data with a function is to use a return value.
Functions that have return values evaluate to that value, in exactly the same way that
variables evaluate to the values they contain when you use them in expressions.
Just like variables, return values have a type.
When a function returns a value, you have to modify your function in two ways:
Specify the type of the return value in the function declaration instead of using the void
keyword.
Use the return keyword to end the function execution and transfer the return value to the
calling code (see sample code below).
98
CIT 351 C#.Net Programming
Local Variables
Invoking or calling a method is actually the process of execution of the method‘s code,
placed into its body.
To invoke a method, write the method‘s name <method_name>, followed by the round
brackets and semicolon ";" at the end: <method_name>();
Parameters
This involves the following code, where you can have any number of parameters, each
with a type and a name:
static < returnType > < functionName > ( < paramType > < paramName > , ...)
{
...
return < returnValue > ;
}
The parameters are separated using commas, and each of these parameters is accessible
from code within the function as a variable.
For example, a simple function might take two double parameters and return their
product:
static double Product(double param1, double param2)
{
return param1 * param2;
}
99
CIT 351 C#.Net Programming
Some examples of program codes and class exercise are described in this
session.
1.0 Introduction
2.0 Objectives
Class Exercise
Write a program that converts a given body temperature, measured in Fahrenheit degrees,
to that temperature and output in Celsius degrees, with the following message: "Your
body temperature in Celsius degrees is X", where X is respectively the Celsius degrees.
In addition if the measured temperature in Celsius is higher than 37 degrees, the program
should warn the user that they are ill, with the following message "You are ill!".
The Celsius to Fahrenheit formula is like this °C = (°F - 32) * 5 / 9,
100
CIT 351 C#.Net Programming
4.0 CONCLUSION
To end this session, the basic unit of execution in a C# program is the statement. A series
of statements surrounded by curly braces form a block of code (i.e. statement
blocks).Comments allow inline documentation of source code. The C# compiler ignores
comments. Three styles of comments are allowed in C#: single-line, multiple-line and
XML documentation-line comments.
5.0 SUMMARY
This unit provided an overview of C# syntax. It equally outlined the styles of comments
allowed in C#. We hope you found this unit enlightening.
102
CIT 351 C#.Net Programming
7.0 CONTENT
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Class example
3.2 Life cycle of an object
3.3 Constructor example
3.4 Destructor example
3.5 Inheritance
3.6 Polymorphism
3.7 Self-Assessment Exercise
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
103
CIT 351 C#.Net Programming
The class keyword is preceded by the access level. Because public is used in this case,
anyone can create objects from this class.
The name of the class follows the class keyword.
The remainder of the definition is the class body, where the behaviour and data are
defined.
Fields, properties, methods, and events on a class are collectively referred to as class
members.
Figure 22 is a representation of the CupOfCoffee class, with five members (properties or fields,
because no distinction is made in UML.
Each of the entries contains the following information:
Accessibility: A + symbol is used for a public member, a - symbol is used for a private member.
The member name .
The type of the member .
object.
Both fields and properties have their types.
Unlike fields, properties are not classified as variables.
You cannot pass a property as a parameter.
Properties are declared in the class block by specifying the access level of the property,
followed by the type of the property, followed by the name of the property, and followed
by a code block that declares a get-accessor and/or a set accessor.
Accessibility determines which code can access these members — that is, whether they
are available to all code (public), only to code within the class (private), or use a more
complex scheme.
One common practice is to make fields private and provide access to them via public
properties.
Methods
In UML, class boxes show methods in the third section, as shown below:
105
CIT 351 C#.Net Programming
The type shown at the end is the return type and method parameters are shown.
Each parameter is displayed in UML with one of the following identifiers: in or out
These are used to signify the direction of data flow.
Everything is an object in C#
Every command you have used so far has been a property or a method, such as:
< String > .Length ,
< String >.ToUpper() , etc.
The period character separates the object instance ‘ s name from the property or method
name.
Apart from the normal state of ― being in use, ‖ every object includes two important
stages:
106
CIT 351 C#.Net Programming
Destructors are used by the .NET Framework to clean up after objects are no longer used.
Generally, you don ‘ t have to provide code for a destructor method; instead, the default
operation does the work for you.
However, you can provide specific instructions if anything important needs to be done
before the object instance is deleted. An example
class Car
{
~Car() // destructor
{
// cleanup statements...
}
}
3.5 Inheritance
107
CIT 351 C#.Net Programming
Inheritance enables you to extend or create more specific classes from a single, more
generic base class (see Figure 25).
For example, from an Animal class that possesses methods such as: EatFood() or Breed(),
you could create a derived class called Cow , which would support all of these methods
and include others like Moo() and SupplyMilk() and others.
The parent class is called the base class, and the class that inherits from the base class is
called the derived class.
C# does not support multiple inheritance though the base class can also be a derived
class.
Accessibility of Members:
Private members of the base class are not accessible from a derived class, but public
members are.protected keyword allows only derived classes to have access to a member.
For external code, this is identical to a private member — it doesn ‘ t have access in
either case.
...
}
class <derived_class> : <base_class>
{
...
}
Example of inheritance
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
3.6 Polymorphism
The ability to treat an instance of derived class as an instance of the base class and being
able to call the operations of the base class using an instance of the derived class is called
Polymorphism.
Polymorphism means one name many forms. Polymorphism means one object behaving
as multiple forms. One function behaves in different forms
109
CIT 351 C#.Net Programming
Define a class Car that contains a field make that stores the make of the car. Define a
non-default constructor that initializes the make of the car when an object of the class is
created. Also define a destructor that prints the message ―Inside the Destructor‖.
Other features of OOP are:
• Inheritance
• Polymorphism
• Relationships between objects
110
CIT 351 C#.Net Programming
• Operator overloading
• Events
• Reference versus value types
4.0 CONCLUSION
5.0 SUMMARY
This unit provided an overview of C# syntax. It equally outlined the styles of comments
allowed in C#. We hope you found this unit enlightening.
13. Stallman, Richard (June 26, 2009). "Why free software shouldn't depend on Mono or
C#".
14. Simon, Raphael; Stapf, Emmanuel; Meyer, Bertrand (June 2002). "Full Eiffel on the
.NET Framework".
15. "The ECMA C# and CLI Standards". 2009 -07-06.
16. Zander, Jason (November 23, 2007). "Couple of Historical Facts".
112
CIT 351 C#.Net Programming
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 How to create a new Window form Applications
3.2 Label and Link controls
3.3 Button Controls
3.4 Textbox Controls
3.5 Building and running GUI applications
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
113
CIT 351 C#.Net Programming
114
CIT 351 C#.Net Programming
Properties
All controls have a number of properties that are used to manipulate the behavior
of the control.
The base class of most controls, System.Windows.Forms.Control , has several
properties that other
controls either inherit directly or override to provide some kind of custom
behavior.
115
CIT 351 C#.Net Programming
These two properties are especially useful when you are designing your form.
Ensuring appropriate adjustment of controls when a window form is resized
The Anchor property specifies how the control behaves when a user resizes the window.
You can specify that the control should resize itself, anchoring itself in proportion to its
own edges, or stay the same size, anchoring its position relative to the window ‘ s edges.
116
CIT 351 C#.Net Programming
Events
117
CIT 351 C#.Net Programming
118
CIT 351 C#.Net Programming
The Button control exists on just about any Windows dialog you can think of.
A button is primarily used to perform three kinds of tasks:
To close a dialog with a state (e.g., the OK and Cancel buttons) .
To perform an action on data entered on a dialog (e.g., clicking Search after entering
some search criteria) .
119
CIT 351 C#.Net Programming
Try out
Double click Class Lecture button, add the following code
private void btnLecture_Click(object sender, EventArgs e)
{
this.Text = "This is a lecture class";
}
120
CIT 351 C#.Net Programming
Textbox control enable users of your application to enter text, such as the TextBox
control
121
CIT 351 C#.Net Programming
9. Text5 (Name:richTextBoxOutput )
10. Button1 (Name: btnOk; Text : OK)
11. Button2 (Name : btnExit ; Text Exit)
122
CIT 351 C#.Net Programming
Type in the code for the Ok click event handler (double click on the Ok control)
Type in the code for the Exit button
After this RUN the form and fill in the details
Click Exit
123
CIT 351 C#.Net Programming
The source code in Figure 1-1 displays the text "Hello World!" in a window. (The C#
version of a command line hello-world application would be a one-liner). As you can see
from the code, C# has a C-based syntax, but with objects like C++ or Java. Every
function in C# is a method of a type. In this example, the MyForm class is defined to
Derive its functionality from the Form class (part of the .NET Framework Class Library).
Class Activity 2
Write the program to make the interface function correctly in see Figure 33.
4.0 CONCLUSION
In conclusion, we able to learn how to create a new windows application , design forms
and add codes behind the click events of some buttons.
5.0 SUMMARY
We considered building a GUI based windows application in this unit with the
knowledge gained.
124
CIT 351 C#.Net Programming
126
CIT 351 C#.Net Programming
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 File Connections
3.2 Database Connections
3.3 Building and Running a Database Application
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
What you would study in this unit, would enable you to:
• Explain the concept of database driven application
• Demonstrate the use of storing information into an external text file
• Give a classic example of a database driven application
• Outline the steps required to build and run a database drivene application
Files can be a great way to store data between instances of your application, or they can
be used to transfer data between applications.
All input and output in the .NET Framework involves the use of streams
A stream is an abstract representation of a serial device A serial device is something that
stores data in a linear manner and is accessed the same way: one byte at a time.
Types of Streams
127
CIT 351 C#.Net Programming
Output:
Output streams are used when data is written to some external destination, which can be a
physical disk file, a network location, a printer, or another program.
Input:
Input streams are used to read data into memory or variables that your program can access. The
most common form of input stream you have worked with so far is the keyboard.
An input stream can come from almost any source eg reading disk files.
128
CIT 351 C#.Net Programming
Class Assignments
MySQL offers a easy connector that will allow you to execute queries to phpmyadmin from
your windows form.
Requirements
MySQL .NET Connector Extension.
Appserv(phpmyadmin)
mysql-connector-net-6.3.0
Add mysql-connector-net-6.3.0
Locate the solution explorer in the right top corner of Visual Studio when your project is open,
use right click on References and then select Add Reference from the context menu.
In the shown menu, navigate to Extensions and select the checkbox from the list the MySql.Data
(MySql.Data.dll) and then click on OK.
131
CIT 351 C#.Net Programming
132
CIT 351 C#.Net Programming
133
CIT 351 C#.Net Programming
4.0 CONCLUSION
In this unit, we learnt that Console applications are the kind of executables that you
would use to create a command line utility. The command line utility could be dir or
xcopy. We equally identified the steps required to build and run a console application.
134
CIT 351 C#.Net Programming
5.0 SUMMARY
In this unit, we considered the concept of console application, the types of command line
utility and a classic example of a console application. We equally identified the steps
required to build and run a console application. Let us attempt the question below.
135