0% found this document useful (0 votes)
13 views47 pages

Chapter 2

Chapter 2 provides an overview of C# programming, highlighting its object-oriented nature and the structure of C# programs, which consist of .cs files that are compiled into executable code. It discusses the Integrated Development Environment (IDE), specifically Visual Studio, and outlines the steps to create a new C# project, including naming conventions and the significance of the Main method. Additionally, it explains the use of the system console for input-output operations in console applications.

Uploaded by

dj games
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views47 pages

Chapter 2

Chapter 2 provides an overview of C# programming, highlighting its object-oriented nature and the structure of C# programs, which consist of .cs files that are compiled into executable code. It discusses the Integrated Development Environment (IDE), specifically Visual Studio, and outlines the steps to create a new C# project, including naming conventions and the significance of the Main method. Additionally, it explains the use of the system console for input-output operations in console applications.

Uploaded by

dj games
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/ 47

Chapter 2

Basics of C# Programming
By
Dr. Sara Tarik
The C# Language
This is a sample text, Insert your desired text here this is a sample text.

■ C# is a modern, general-purpose, object-oriented, high-level programming language. It is similar to


that of C and C++.

■ The C# programs consist of one or several files with a .cs extension, which contain definitions of
classes and other types.

■ These files are compiled by the C# compiler (csc) to executable code and as a result assemblies are
created, which are files with the same name but with a different extension (.exe or .dll).

■ For example, if we compile HelloCSharp.cs, we will get a file with the name HelloCSharp.exe.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 2


The C# Language
This is a sample text, Insert your desired text here this is a sample text.

■ The main program elements in C# are classes, methods, operators, expressions, conditional
statements, loops, data types, exceptions and few others.

■ C# has a rich set of keywords that are reserved and cannot be used as identifiers (variable names,
class names, etc.). These keywords are used in the definition of the program elements. Below are
examples of the main keywords in C#:

using namespace class void this public protected private


int uint short ushort float double char string
long ulong bool byte sbyte enum struct const
if else switch case for foreach while do
break continue goto true false null new return
try catch throw sizeof typeof params abstract interface
WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 3
The C# Language
This is a sample text, Insert your desired text here this is a sample text.

■ The C# language is case-sensitive.


■ It distinguishes between uppercase and lowercase letters so we should use the correct casing when
we write C# code.

■ Be careful when writing the keywords like class, static, void, int, etc.
■ The same thing, written in upper case, lower-case or a mix of both, means different things in C#.
■ Writing Class is different from class and void is different from VOID.
■ This rule applies to all elements of your program: keywords, names of variables, class names etc.
■ All C# keywords are lowercase (e.g., public, class, void), while namespaces, class begin (by
convention) with an initial capital letter and have capitalized the first letter of any embedded words
(e.g., Console.WriteLine, System.Windows. MessageBox, System.Data.SqlClient).
WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 4
Integrated Development Environment
This is a sample text, Insert your desired text here this is a sample text.

■ An Integrated Development Environment (IDE) is a combination of traditional tools for the


development of software applications.

■ IDE is a tool where we write code, compile it, run it, test it, debug it, etc. and everything is integrated
into a single place.

■ Development environments integrate in them a text editor for writing code, a programming
language, a compiler or an interpreter and a runtime environment for executing programs, a
debugger for tracking the program and seeking out errors, tools for user interface design and other
tools.

■ For programming with the C# language the most commonly used IDE is Visual Studio, which is
developed and distributed freely by Microsoft and can be downloaded from: https://www.
visualstudio.com/downloads.
WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 5
What Is Visual Studio?
This is a sample text, Insert your desired text here this is a sample text.

■ Visual Studio is a powerful IDE for developing software applications for Windows and the .NET
Framework platform.

■ Visual Studio supports different programming languages (for example C#, VB.NET and C++) and
different software development technologies such as Win32, ASP.NET, ADO.NET, Windows Forms,
WPF, Silverlight, Windows Store apps and many more Windows and .NET technologies.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 6


What Is Visual Studio?
This is a sample text, Insert your desired text here this is a sample text.

■ Below are the main windows you will


commonly use in Visual Studio when
working with C#:

1) Start Page: The initial screen that


appears when you open the Visual
Studio IDE. It displays a list of recently
accessed projects. From the start page
we can quickly start a new project and
access previously created projects or
solutions.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 7


What Is Visual Studio?
This is a sample text, Insert your desired text here this is a sample text.

2) Code Editor: The primary window for


writing and editing C# code. It allows
opening and editing multiple files.
3) Solution Explorer: Displays the
structure of our project, including files
it contains, references, and folders. It is
used to navigate through files, open
files for editing; and add, remove, and
manage files and references. When no
project is loaded, this window is empty.
4) Error List: Lists errors, warnings, and messages detected in the program we develop (if any).
Click on an error to navigate to its location in the code.
WhirlWind P O W E R P O I N T T E M P L A T E | Email : [email protected] | Web : www.example.com 8
Creating a New C# Project
This is a sample text, Insert your desired text here this is a sample text.

■ We must create a new project or load an


existing one. The project groups many files,
designed to implement a software
application. It is recommended that we create
a separate project for each new program.

■ We can create a project in Visual Studio by


following these steps:

1) Open Visual Studio. From the Start


Window, select Create a new project.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 9


Creating a New C# Project
This is a sample text, Insert your desired text here this is a sample text.

2) In the Create a new project dialog, use the


Search bar to type C#.

3) Select the desired template (e.g., Console


App for a basic application). Console
applications are programs which use the
console as a default input and output. Data
is entered with the keyboard and when a
result needs to be printed it appears on
the console (as text on the screen in the
program window).

4) Click Next.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 10


Creating a New C# Project
This is a sample text, Insert your desired text here this is a sample text.

5) Fill in the following details to configure


the Project:

● In Project Name: Enter a name for your


project (e.g., IntroToCSharp).

● In Location: Choose where to save the


project.

6) Click Create.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 11


Creating a New C# Project
This is a sample text, Insert your desired text here this is a sample text.

■ The newly created project is now


shown in the Solution Explorer.

■ Also, our first file, containing the


program code, is automatically
added. It is named Program.cs.

■ It is very important to give


meaningful names to our files,
classes, methods and other
elements of the program, so that we
can easily find them and navigate
the code.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 12


Creating a New C# Project
This is a sample text, Insert your desired text here this is a sample text.

■ A meaningful name means a name


that answers the question “what is
the purpose of this file / class /
method / variable?” and helps
developers to understand how the
code works.

■ If your project is well named, after


few months or a year you will be
able to explain what it is intended
to do without opening it and
looking inside.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 13


Creating a New C# Project
This is a sample text, Insert your desired text here this is a sample text.

■ In order to rename the Program.cs


file, right click on it in the Solution
Explorer and select "Rename". We
can name the main file of our C#
program HelloCSharp.cs.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 14


Creating a New C# Project
This is a sample text, Insert your desired text here this is a sample text.

■ A dialog window appears asking us if


we want to rename class name as
well as the file name. We select "Yes".

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 15


Creating a New C# Project
This is a sample text, Insert your desired text here this is a sample text.

■ After we complete all these steps we


have our first console application
named IntroToCSharp and containing
a single class HelloCSharp (stored in
the file HelloCSharp.cs).
■ By default, the HelloCSharp.cs code
should be loaded and ready for
editing.
■ If it is not, we double click on the
HelloCSharp.cs file in the Solution
Explorer to load it.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 16


using Directive
This is a sample text, Insert your desired text here this is a sample text.

■ A great strength of C# is its rich set of


predefined classes that we can reuse.
■ These classes are grouped and
organized under namespaces—named
collections of related classes.
■ Visual Studio automatically inserts 5
using statements in the code and thus
5 namespaces.
■ Each using directive identifies a
namespace containing classes that a
C# app should be able to use.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 17


using Directive
This is a sample text, Insert your desired text here this is a sample text.

■ Each using statement tells the


compiler where to look for a class
that’s used in this app.
■ System is a namespace that contains
many classes including the class
named Console that will be used next
and many other useful classes.
■ In this case, only the System
namespace is needed and you are
allowed to delete the 4 others to make
the code more readable.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 18


Class Definition
This is a sample text, Insert your desired text here this is a sample text.

■ The simplest definition of a class consists


of the keyword class, followed by its name.

■ A keyword is a word in code that is


reserved by C# for a specific use.

■ Every C# program consists of at least one


class, here called HelloCSharp.

■ A class consists of variables and methods.


The content of the class is located in a
block of program lines, surrounded by
curly brackets { }. In this case, the class has
only one method called Main( ).
WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 19
Class Name Convention
This is a sample text, Insert your desired text here this is a sample text.

■ A class name is an identifier—a series of


characters consisting of letters, digits, and
underscores (_) that does not begin with a
digit and does not contain spaces.

■ All class names begin with a capital letter


and capitalize the first letter of each word
they include (e.g., SampleClassName).

■ Some valid identifiers are Class1, MyClass


identifier, _value and m_Class1.

■ The name 1Class is not a valid identifier because it begins with a digit, and the
name My Class is not a valid identifier because it contains a space.
WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 20
Main Method Definition
This is a sample text, Insert your desired text here this is a sample text.

■ Every program written in C# starts from a


Main method that can be written in two
ways:
● static void Main(string[] args) – with
parameters from the command line. It
must have only one parameter of type
array of string. The parameter is called
args but that isn’t mandatory. This
parameter is not used in most cases so it
can be omitted.
● static void Main( ) – without parameters
from the command line.
WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 21
Main Method Definition
This is a sample text, Insert your desired text here this is a sample text.

■ The Main method must be static and void,


and it must have a name Main.
■ Static members are scoped to the class
level (rather than the object level) and can
thus be invoked without the need to first
create a new class instance.

■ If any of the aforementioned requirements


is not met, the program will compile but it
will not start because the starting point is
not defined correctly.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 22


Main Method Definition
This is a sample text, Insert your desired text here this is a sample text.

■ When creating a console application, Visual


Studio uses the first way by default, which
we can edit manually if we want to, and
delete the part with the parameters
string[] args.

■ Class declarations normally contain one or


more methods.

■ Method names usually follow the same


capitalization conventions used for class
names.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 23


Main Method Definition
This is a sample text, Insert your desired text here this is a sample text.

■ The content of every method is found after


its signature, surrounded by opening and
closing curly brackets.

■ All we have to do is add code to the Main


method.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 24


The System Console
This is a sample text, Insert your desired text here this is a sample text.

■ The system console is a window of the


operating system through which users can
interact with system programs of the
operating system.

■ Generally, the system console represents a


text terminal, which means that it accepts
and visualizes just text without any
graphical elements like buttons, menus,
etc.

■ It usually looks like a black colored


window like this one:

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 25


The System Console
This is a sample text, Insert your desired text here this is a sample text.

■ The interaction consists of text input from


the standard input (usually keyboard) or
text display on the standard output
(usually on the computer screen).

■ These actions are also known as input-


output operations.

■ For each console application the operating


system connects input and output devices.

■ By default these are the keyboard and the


screen.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 26


The System Console
This is a sample text, Insert your desired text here this is a sample text.

■ Modern communication methods are many and various: they can be through graphical or web-based
interface, console or others.

■ The console remains an irreplaceable tool for communication with the user espicially when:
● We write small and simple programs where it is necessary to focus the attention on the specific
problem to be solved, rather than the elegant representation of the result to the user.

● We want to test a small piece of code for a larger application. Due to simplicity of the operation of
the console application we can isolate this part of the code easily and comfortably without having
to go through a complex user interface and a number of screens to get to the desired code for
testing.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 27


Console Output
This is a sample text, Insert your desired text here this is a sample text.

■ In C#, the console output is used to display information to the console window.
■ The Console class in the System namespace provides methods to output text and data to the console.
■ Console.WriteLine(…) method prints a line of text and moves the cursor to the next line. It is used to
print various data types because for each type there is a predefined version of this method in the
Console class.

Output:

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 28


Console Output
This is a sample text, Insert your desired text here this is a sample text.

■ On the other hand, Console.Write(…) method prints a line of text without moving the cursor to the
next line.

Output:

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 29


Program 1: Displaying a Single Line of Text
This is a sample text, Insert your desired text here this is a sample text.

■ Let’s consider a simple app that displays a line


of text.

■ Note that in C#, most statements end with a


semicolon. It tells the compiler where the
statement ends.

■ As mentioned before, Console is a class in the


System namespace.

■ A class’s full name consists of the namespace


where the class is grouped and the class name,
for example System.Console.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 30


Program 1: Displaying a Single Line of Text
This is a sample text, Insert your desired text here this is a sample text.

■ Since using System statement is included in


the program, classes in this namespace can be
referenced by the class name only as follows:
Console.WriteLine(“ Hello C#!”);

■ Instead of the full name


System.Console.WriteLine(“ Hello C#!”);

■ WriteLine is actually a method in the class


Console which is used to display a line of text
in the console window.

■ The string in the parentheses, between the double quotation marks, in line 8 is the argument to the
method.
WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 31
Program 1: Displaying a Single Line of Text
This is a sample text, Insert your desired text here this is a sample text.

■ Method Console.WriteLine performs its task


by displaying its argument in the console
window.

■ When Console.WriteLine completes its task, it


positions the screen cursor at the beginning of
the next line in the console window.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 32


Starting the Project
This is a sample text, Insert your desired text here this is a sample text.

■ To start the project, press [Ctrl+F5].


■ The program will start and the result will
be displayed on the console, followed by
the "Press any key to continue . . ."
message.

■ The last message is not part of the result


produced by the program. It is a reminder
by Visual Studio that our program has
finished its execution and it gives us time
to see the result.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 33


Starting the Project
This is a sample text, Insert your desired text here this is a sample text.

■ If we run the program by only pressing


[F5], that message will not appear and the
result will vanish instantly after appearing
because the program will have finished its
execution, and the window will be closed.

■ That is why we should always start our


console applications by pressing [Ctrl+F5].

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 34


Main Formatting Rules
This is a sample text, Insert your desired text here this is a sample text.

■ Formatting is adding characters such as spaces, tabs and new lines, which are insignificant to the
compiler and they give the code a logical structure and make it easier to read.
■ The program code must be correctly formatted:
● All class and method names must start with a capital letter.
● Variable names must begin with a lower-case letter.
● We must follow several important rules regarding indentation: when some piece of code is
logically inside another piece of code, it is indented (moved) on the right with a single [Tab]. For
example, 1) Methods are indented inside the definition of the class (move to the right by one or
more [Tab] characters). 2) Method contents are indented inside the definition of the method. 3)
The opening curly bracket { must be on its own line and placed exactly under the method or class it
refers to. 4) The closing curly bracket } must be on its own line, placed exactly vertically under the
respective opening bracket (with the same indentation).
WhirlWind P O W E R P O I N T T E M P L A T E | Email : [email protected] | Web : www.example.com 35
Main Formatting Rules
This is a sample text, Insert your desired text here this is a sample text.

■ The examples below show the difference between the formatted and unformatted code.
A properly formatted code The code is written without tabs

A randomly formatted code The code is written on the same line

■ The unformatted code with inconsistent indentation, spacing, and alignment will compile and run
exactly like the formatted code but they are more difficult to read and understand, and therefore
difficult to modify and maintain.
WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 36
Compiling the Source Code
This is a sample text, Insert your desired text here this is a sample text.

■ The compiling process in Visual Studio


includes several steps:
● Syntax error check.
● A check for other errors, like missing
libraries.
● Converting the C# code into an
executable file (a .NET assembly). For
console applications it is an .exe file.
■ To compile a file in Visual Studio, we press
the [F6] key or [Shift+Ctrl+B].

■ Usually, errors are underlined in red, to attract the programmer’s attention.


WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 37
Compiling the Source Code
This is a sample text, Insert your desired text here this is a sample text.

■ Errors are listed in the "Error List" window


if it is visible (if it is not, we can show it
from the "View" menu of Visual Studio).

■ If our project has at least one error, it will


be marked with a small red "x" in the
"Error List" window. Short info about the
problem is displayed for each error –
filename, line number and project name.

■ If we double click any of the errors in the


"Error List", Visual Studio will
automatically take us to the file and line of code where the error has occurred.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 38


Debugging the Program
This is a sample text, Insert your desired text here this is a sample text.

■ When our program contains errors, also known as bugs, we must find and remove them, i.e. we need
to debug the program.

■ The debugging process includes:


● Finding the code causing the problems.
● Fixing the code so that the program works correctly.
● Testing to make sure the program works as expected after the changes are made.
■ The process can be repeated several times until the program starts working correctly.
■ Visual Studio can help by allowing us to check step by step whether everything is working as
planned.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 39


Debugging the Program
This is a sample text, Insert your desired text here this is a sample text.

■ To stop the execution of the program at designated positions we can place breakpoints.
■ The breakpoint is associated with a line of the program.
■ The program stops its execution on the lines with breakpoints, allowing for the rest of the code to be
executed step by step.

■ On each step, we can check and even change the values of the current variables.
■ Debugging is a sort of step by step slow motion execution of the program. It gives us the opportunity
to easily understand the details of the code and see where exactly and why the errors have occurred.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 40


Debugging the Program
This is a sample text, Insert your desired text here this is a sample text.

■ To illustrate how to use breakpoints,


let’s create an intentional error in our
program,

■ We will add a line to the program,


which will create an exception during
the execution.

■ When we start the program again with


[Ctrl+F5] we will get an error and it will
be printed on the console.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 41


Debugging the Program
This is a sample text, Insert your desired text here this is a sample text.

■ Move the cursor to the line with the


opening bracket of the Main() method
and press [F9] (by doing so we place a
breakpoint on that line).

■ A red dot appears, indicating that the


program will stop there if it is executed
in debug mode.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 42


Debugging the Program
This is a sample text, Insert your desired text here this is a sample text.

■ Now we must start the program in debug


mode: Select Debug -> Start Debugging or
press [F5].

■ The program will start and immediately stop


at the first breakpoint it encounters.

■ The line will be colored in yellow and we can


execute the program step by step.
■ With the [F10] key we move to the next line. When we
are on a given line and it is colored in yellow, the code
on that line is not executed yet. It executes once we
have passed that line.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 43


Debugging the Program
This is a sample text, Insert your desired text here this is a sample text.

■ We press [F10] one more time to execute the


current line.

■ This time Visual Studio displays a window


specifying the line, where the error occurred
as well as some additional details about it.

■ Once we know where exactly the problem in


the program is, we can easily correct it.

■ To do so, first, stop the execution of the program before it is finished. We select Debug –> Stop
Debugging or press [Shift+F5]. After that we delete the problem line and start the program in
normal mode (without debugging) by pressing [Ctrl+F5].

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 44


Comments
This is a sample text, Insert your desired text here this is a sample text.

■ Comments are explanatory statements that can be included in the C# code to help anyone reading
the source code (improve code readability).

■ All characters available inside any comment are ignored by the C# compiler. So, they do not cause the
computer to perform any action when the app executes.

■ There are two common types of comments in C#: single-line comments and multi-line comments.
■ The single-line comment starts with // , terminates at the end of the line on which it appears, and can
be placed anywhere in the line.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 45


Comments
This is a sample text, Insert your desired text here this is a sample text.

■ The multiline (delimited) comments starts with the delimiter /* and ends with the delimiter */.
■ Delimited comments can be split over several lines and all text between the delimiters is ignored by
the compiler.

WhirlWind POW ERPOINT TEMPLATE | Email : [email protected] | Web : www.example.com 46

You might also like