[go: up one dir, main page]

0% found this document useful (0 votes)
348 views32 pages

Edx C# Course

The document outlines a course on C# programming organized into 4 modules. Module 1 introduces C# and the development tools used for C#, including Visual Studio, Xamarin, MonoDevelop, TextPad and Notepad. It covers data types, variables, operators, statements and decision statements. Module 2 covers repetition and control flow statements. Module 3 covers methods, exception handling, and editors. Module 4 concludes the course with a post-course survey.

Uploaded by

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

Edx C# Course

The document outlines a course on C# programming organized into 4 modules. Module 1 introduces C# and the development tools used for C#, including Visual Studio, Xamarin, MonoDevelop, TextPad and Notepad. It covers data types, variables, operators, statements and decision statements. Module 2 covers repetition and control flow statements. Module 3 covers methods, exception handling, and editors. Module 4 concludes the course with a post-course survey.

Uploaded by

Pavan Sai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 32

Course outline

Module 0: Course introduction

 Before you Start

 Pre-Course Survey

 Course Welcome and Introduction

module 1

1. Introducing C#

 Introduction

 A History of C#

 .NET Framework Overview

2. The Tools

 Visual Studio

 Xamarin

 MonoDevelop

 TextPad

 Notepad

 A Tour of Visual Studio

3. Data Types, Variables, Operators, and Statements


 Data Types

 Statements

 Identifiers

 Operators

 Data Type Conversions

 Demo: Data Types

 Self-Check Questions

4. Module Lab

 Tutorial Lab

 Self-Assessment Lab

 Lab Assessment Questions

module 2

1. Decision Statements

 Lesson Introduction

 The if Statement

 Self-Check

 The switch Statement

 Self-Check

2. Repetition in C#
 Introducing Repetition

 The for Loop

 The while Loop

 The do Loop

 Demo: Control Statements

 Self-Check

 Self-Check

3. Module Lab

 Tutorial Lab 1 Using if Statements

 Tutorial Lab 2 Using a switch Statement

 Tutorial Lab 3 Using a for Loop

 Tutorial Lab 4 Using while and do Loops

 Self-Assessment Lab

Module 3

1. Introducing Editors

 Module Introduction

2. Methods

 Method Declarations

 Calling Methods

 Returning Data from Methods


 Method Overloading

 Optional and Named Parameters

 Demo: Methods

 Self-Check

 Self-Check

3. Exception Handling

 Introducing Exception Handling

 Exception Propagation

 Handling Exceptions

 The finally Block

 Throwing Exceptions

 Demo: Exception Handling

 Self-Check

 Self-Check

4. Module Lab

 Tutorial Lab 1 Creating and Using Methods

 Tutorial Lab 2 Exception Handling

 Self-Assessment Lab

Module 4: Course Conclusion

1. Post-Course Survey
For more information , you can see: Visual Studio: https://aka.ms/edx-dev204x-
vs01

MonoDevelop
MonoDevelop is another toolset that you can use to create
applications with C#. It is positioned as a cross platform IDE that
allows you to write desktop or web applications that can run on Linux,
Windows, and Mac OS X.

MonoDevelop offers the following features:

Multi-platform support

Code completion

Integrated debugger

GTK# Visual Designer

Source Control

Unit Testing

Packaging and Deployment

Find it at http://www.monodevelop.com

TextPad
TextPad has been around for many years and is sometimes known as
The Text Editor for Windows. TextPad is essentially a plain text editor
that runs on Windows. It supports different programming and scripting
languages through add-ons known as clip libraries, dictionaries,
macros, and syntax definitions. When using TextPad to write C# code,
you'll be most interested in the Syntax Definitions that provide the
keyword color highlighting.
Choosing a tool like TextPad means that you have a lightweight editor
for your C# code files but it also means that you don't get the full
benefits of an IDE and as such you will be responsible for:

 Managing multiple files for your project

 Compiling the code using the command-line compiler tools from


Microsoft

 Manual debugging of the code through code review

 Manual deployment of the application

You can download TextPad at this


URL, http://www.textpad.com/download/.

Notepad
Of course Microsoft Windows has the venerable Notepad app included
with every copy. You can write your code in Notepad and then use the
command-line compiler csc.exe to compile your code.

Take note that you will not realize any benefits such as code
completion, Intellisense, syntax highlighting, or complete project
solution and file management. And you will need to learn the available
options and switches for the command line compiler.

https://courses.edx.org/courses/course-
v1:Microsoft+DEV204.1x+4T2017/courseware/6ff2f1e658134f31bb8293
a370a26c73/31bd8f463a574601b7ff2ed9cf6d0127/?child=first

Data Types
Bookmarked
Data Types
All applications store and manipulate data within the computer's
memory. C# supports two kinds of data types used to represent real-
world information, value types and reference types.

Value types are so-called because they contain the actual value of the
data they store. For example, you might have an int type that stores
the value 3. The literal value of 3 is stored in the variable that you
declare to hold it.

With the exception of DateTime and string, in the below table,the data
types listed are aliases for structs in .NET that represent the data
types in the Microsoft .NET Framework. Anyplace you can use int you
can also use System.Int32. We'll cover structs in module four.

Reference types are also known as objects. Reference types are


created from class files, which are covered in the Object-Oriented
Programming in C# course.

A reference type stores a reference to the location in memory of the


object. If you are familiar with C/C++ then you can think of a reference
to the memory location to be the same as a pointer. C# does not
require you to use pointers.

The following table shows the most commonly used value types.

Type Description Size (bytes) .NET Type

int Whole numbers 4 System.Int32 -2,14

long Whole numbers (bigger range) 8 System.Int64 -9,22


float Floating-point numbers 4 System.Single +/-3.

double Double precision (more accurate) floating-point numbers 8 System.Double +/-1.

decimal Monetary values 16 System.Decimal 28 si

char Single character 2 System.Char N/A

bool Boolean 1 System.Boolean True

DateTime Moments in time 8 System.DateTime 0:00

string Sequence of characters 2 per character System.String N/A

For more information , you can visit the MSDN web


site, http://msdn.microsoft.com, for documentation in C# supported data
types.

Statements
Bookmarked

Statements
In C#, a statement is considered a command. Statements perform
some action in your code such as calling a method or performing
calculations. Statements are also used to declare variables and assign
values to them.

Statements are formed from tokens. These tokens can be keywords,


identifiers (variables), operators, and the statement terminator which
is the semicolon (;). All statements in C# must be terminated with a
semicolon.

Example:

int myVariable = 2;

In this example, the tokens are:

 int

 myVariable

 =

 2

 ;

int is the data type used for the variable called myVariable.

The '=' is an assignment operator and is used to set the value of


myVariable to 2.

The numeral 2 is known as a literal value. Literal simply means that it


is, what it says it is. The numeral 2 cannot be anything but the numeral
2. You cannot assign a value to 2. You can assign the numeral 2 to a
variable however, and that is what this C# statement is doing.

Finally, the statement ends with a semi-colon.

Identifiers
Bookmarked

Identifiers
In C#, an identifier is a name you give to the elements in your program.
Elements in your program include;

 Namespaces - the .NET Framework uses namespaces as a way to


separate class files into related buckets or categories. it also helps
avoid naming collisions in applications that may contain classes with
the same name

 Classes - classes are the blueprints for reference types. They


specify the structure an object will take when you create instances of
the class

 Methods - covered a bit later in the course, they are discrete


pieces of functionality in an application. They are analogous to
functions in the non-object-oriented programming world

 Variables - these are identifiers or names, that you create to hold


values or references to objects in your code. A variable is essentially a
named memory location

When you create a variable in C# you must give it a data type. The data
type tells the compiler and syntax checker what kind of information
you intend to store in that variable. If you try to assign data that is not
of that type, warnings or errors will inform you of this. This is part of
the type-safe nature of C#.

You can assign a value to the variable at the time you create it or later
in your program code. C# will not allow you to use an unassigned
variable to help prevent unwanted data from being used in your
application. The following code sample demonstrates declaring a
variable and assigning a value to it.

int myVar = 0;

C# has some restrictions around identifiers that you need to be aware


of.
First off, identifiers are case-sensitive because C# is a case-sensitive
language. That means that identifiers such as myVar, _myVar,
and myvar, are considered different identifiers.

Identifiers can only contain letters (upper case or lowercase), digits,


and the underscore character. You can only start an identifier with a
letter or an underscore character. You cannot start the identifier with a
digit. myVar and _myVar are legal but 2Vars is not.

C# has a set of reserved keywords that the language uses. You should
not use these keywords as an identifier in your code. You may choose
to take advantage of the case-sensitivity of C# and use Double as an
identifier to distinguish it from the reserved keyword double, but that
is not a recommended approach.

The following table contains the C# reserved keywords.

abstract As Base

byte Case catch char

class const continue Decimal

delegate do Double Else

explicit Extern false finally

float for foreach Goto

implicit in in (generic modifier) Int

is Lock long namespace

null object operator Out

override params Private Protected


ref Return sbyte sealed

sizeof stackalloc static String

switch this Throw True

uint Ulong unchecked unsafe

using virtual void Volatile

Operators
Bookmarked

Operators
When writing C# code, you will often use operators. An operator is a
token that applies to operations on one or more operands in an
expression. An expression can be part of a statement, or the
entire statement. Examples include:

3 + 4 – an expression that will result in the literal value 4 being added


to the literal value 3

counter++ – an expression that will result in the variable (counter)


being incremented by one

Not all operators are appropriate for all data types in C#. As an
example, in the preceding list the + operator was used to sum two
numbers. You can use the same operator to combine two strings into
one such as:

“Tom” + “Sawyer” which will result in a new string TomSawyer


You cannot use the increment operator (++) on strings however. In
other words, the following example would cause an error in C#.

“Tom”++

The following table lists the C# operators by type.

Type

Arithmetic +, -, , /, %

Increment, decrement ++, --

Comparison ==, !=, <, >, <=, >=, is

String concatenation +

Logical/bitwise operations &, |, ^, !, ~, &&, ||

Indexing (counting starts from element 0) []

Casting ( ), as

Assignment =, +=, -=, =, /=, %=, &=,

Bit shift <<, >>

Type information sizeof, typeof

Delegate concatenation and removal +, -

Overflow exception control checked, unchecked

Indirection and Address (unsafe code only) *, ->, [ ], &

Conditional (ternary operator) ?:

Data Type Conversion


Bookmarked

Data Conversions
C# supports two inherent types of conversion (casting) for data types,
implicit and explicit. C# will use implicit conversion where it can,
mostly in the case when a conversion will not result in a loss of data
or when the conversion is possible with a compatible data type. The
following is an example of an implicit data conversion.

Converting from smaller to larger integral types:

int myInt = 2147483647;

long myLong= myInt;

The long type has a 64-bit size in memory while the int type uses 32-
bits. Therefore, the long can easily accommodate any value stored in
the int type. Going from a long to an int may result in data loss
however and you should use explicit casting for that if you know what
data will be lost and it doesn't impact your code.

Explicit casts are accomplished in one of two ways as demonstrated


with the following code sample.

double myDouble = 1234.6;

int myInt;

// Cast double to int by placing the type modifier ahead of the type to be
converted

// in parentheses

myInt = (int)myDouble;

The second option is to use the methods provided in the .NET


Framework.

double myDouble = 1234.6;

int myInt;
// Cast double to int by using the Convert class and the ToInt32() method.

// This converts the double value to a 32-bit signed integer

myInt = Convert.ToInt32(myDouble);

You will find many other methods in the Convert class that cast to
different integral data types such as ToBoolean(), ToByte(), ToChar(),
etc.

The Convert.ToInt32() method can also be used to cast a string literal


to a numeric data type. For example, you may have GUI-based
application in which uses input data into text boxes. These values are
string values when passed to the code in your application. Use of the
above method to cast the string to numbers can help prevent
exceptions in your code when trying to use the wrong data type in a
specific area.

C# also provides another mechanism to deal with casting types. The


use of the TryParse() method and Parse() methods can help with
casting as well. These methods are attached to the types in C# rather
than the Convert class. An example will help demonstrate.

// TryParse() example

bool result = Int32.TryParse(value, out number);

// Parse() example

int number = Int32.Parse(value);

In the TryParse() example, the method returns a Boolean result


indicating if the conversion succeeded. In the Parse() example, if the
conversion does not succeed, an exception will be thrown.
Tutorial Lab for Module 1

Visual Studio Steps

1. Open Visual Studio

2. Select File, New, Project

3. From the Templates section, select Visual C#

4. Select Console App (.NET Framework if using VS 2017 or later)

5. Name your project, such as Mod1_Lab1

6. Choose a location to store the project

7. Click the OK button and Visual Studio will create a new C#


Console application project for you and opens Program.cs for you in the
editor window

8. Place your cursor immediately after the open curly brace in the Main
method, then press enter to create a new line

9. Enter the following code to create variables of different data


types, assign values, and output the results to the Console window:

10. // create variables of different data types

11. // initialize with a "default" value

12. string firstName = "";

13. string lastName = "";

14. int age = 0;

15. string street = "";

16. string city = "";

17. string country = "";


18. DateTime birthDate;

19.

20. // Assign some values

21. firstName = "Tom";

22. lastName = "Thumb";

23. age = 18;

24. street = "123 Fourth Street";

25. city = "Anytown";

26. country = "MyCountry";

27. birthDate = new DateTime(1932, 6, 1);

28.

29. // output to the console window

30.

31. // use simple output with just variable name

32. Console.WriteLine(firstName);

33. Console.WriteLine(lastName);

34.

35. // use placeholder style

36. Console.WriteLine("{0} years old.", age);

37.

38. // use string concatenation

39. Console.WriteLine(street + ", " + city + ", " + country);


40.

41. // use string interpolation


// NOTE: This line of code only works with Visual Studio 2015 or C# 6.0
and later.
// If you are using an earlier version, then comment out this line of code.

Console.WriteLine($"Born on {birthDate}");

NOTE: It is highly recommended that you actually type in the code and
not simply copy and paste. Typing in the code allows you to evaluate
the syntax as you enter it and helps to reinforce your learning along
the way.

1. Press the CTRL+F5 keys to start the application without debugging, or,
using the menus, select Debug then Start Without Debugging.

2. This will cause Visual Studio to compile the code and the run the
application. A console window will open displaying the results if no errors are
encountered.

If you are not using Visual Studio, you will need to follow the
instructions for your specific IDE to create a new project or use the
compiler instructions to compile the C# code file that you
will created in your editor of choice.

The code you need to enter will depend on the editor you are using. For
example, if you are using a text editor, you will need to add the
surrounding structure in addition to above code.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;
namespace Mod1_Lab1

class Program

static void Main(string[] args)

// create variables of different data types

// initialize with a "default" value

string firstName = "";

string lastName = "";

int age = 0;

string street = "";

string city = "";

string country = "";

DateTime birthDate;

// Assign some values

firstName = "Tom";

lastName = "Thumb";

age = 18;

street = "123 Fourth Street";


city = "Anytown";

country = "MyCountry";

birthDate = new DateTime(1932, 6, 1);

// output to the console window

// use simple output with just variable name

Console.WriteLine(firstName);

Console.WriteLine(lastName);

// use placeholder style

Console.WriteLine("{0} years old.", age);

// use string concatenation

Console.WriteLine(street + ", " + city + ", " + country);

// use string interpolation

Console.WriteLine($"Born on {birthDate}");

}
Self Assessment Lab
Bookmarked

Module One Assignment


For this module, you have learned about the data types, operators, and
statements in C#.

Using this knowledge you will start to form some of the foundation for
a potential application. This assignment is designed to allow you to
focus on the data types that are appropriate for attributes of real-
world objects. Later in your C# studies, you will start to combine these
attributes with behaviors (methods) and then transition them into
object-oriented classes.

Also, this assignment offers suggestions for attributes for each object
but does not give explicit instructions on every field required. You will
be required to think through the attributes of these "objects" as you
create the necessary data to support them in an application. Your list
may be different in an application that you would create on your own.
You can use the different listed objects for more practice if you want.

1. Create a C# Console application.

2. Within the Main() method in this application, create variables of


the correct data type for the information related to a course, using the
information presented below.

Student Information

First Name Last Name Birthdate Address Line 1 Address Line 2 City St

Teacher Information
First Name Last Name Birthdate Address Line 1 Address Line 2 City St

UProgram Information

Program Name Department Head

Degree Information

Degree Name Credits Required

Course Information

Course Name Credits Duration in Weeks

3. Once you have the variables created, use assignment statements to


assign values to the variables and use the Console.WriteLine() method to
output the values to the console window.

Again, this assignment is merely intended to check your understanding


of how to create variables, assign values to them, and output the
information to a console window. You will build on these concepts and
begin to create more functionality in later modules.

Challenge (Not graded)

Investigate the .NET Framework documentation around


Console.ReadLine() and modify your code to use this method for
accepting input from a user of your application. Using
Console.ReadLine(), prompt a user for information about a student.
One prompt for each student variable you created earlier. Use the
appropriate code to assign the values from the user to the variables for
the student.

Introducing Decision Statements


Bookmark this page

Introduction
C# decision structures provide logic in your application code that
allows the execution of different sections of code depending on the
state of data in the application. You might ask users whether they wish
to save any changes to a file that is open in the application. The
decision structure permits you to code behavior to execute based on
the answer provided by the user. Visual C# uses conditional
statements to achieve this functionality.

The primary conditional statement in Visual C# is the if statement. An


alternative to the if statement is a switch statement. As you will see in
the section on the switch statement, you might want to use it for more
complex decisions.

The if Statement
Bookmark this page

C# if Statements
In C#, if statements are concerned with Boolean logic. If the statement
is true, the block of code associated with the if statement is executed.
If the statement is false, control either falls through to the line after
the if statement, or after the closing curly brace of an if statement
block.

The following code sample demonstrates an if statement to determine


if a response contains a value of yes.
//if statement

string response = "Yes";

if (response == "Yes")

// statements that will execute if the value of the response variable is

// yes, will be placed here.

Note the use of curly braces in the code sample. You can eliminate the
curly braces if your statement to execute is a single line statement. C#
understands that if no curly braces are used, the line immediately
after the if(condition) will be executed if the condition is true.
Otherwise, it is not. To avoid confusion as to which lines will execute
for a true condition, a recommended practice is to always use curly
braces for your if statement.

In C#, if statements can also have associated else clauses. The else
clause executes when the if statement is false.

The following code example shows how to use an if else statement to


execute code when a condition is false.

//if else Statements

string response;

if (response == "connection_failed")

{
// Block of code executes if the value of the response variable is
"connection_failed".

else

// Block of code executes if the value of the response variable is not


"connection_failed".

if statements can also have associated else if clauses. The clauses


are tested in the order that they appear in the code
after the if statement. If any of the clauses returns true, the block of
code associated with that statement is executed and control leaves
the block of code associated with the entire if construct.

The following code example shows how to use an if statement with an


else if clause.

//else if Statements

string response;

if (response == "connection_failed")

// Block of code executes if the value of the response variable is


"connection_failed".

else if (response == "connection_error")

{
// Block of code executes if the value of the response variable is
"connection_error".

else

// Block of code executes if the value of the response variable is neither


above responses.

You can create as many else if blocks as necessary for your logic, or
until you become completely lost from too many else if clauses. If you
require any more than five else if clauses, you might want to consider
the switch statement, presented next.

The switch Statement


Bookmark this page

The switch statement


If there are too many else if statements, code can become messy and
difficult to follow. In this scenario, a better solution is to use a switch
statement. The switch statement simply replaces multiple else if
statements.

The following sample shows how you can use a switch statement to
replace a collection of else if clauses.

//switch Statement

string response;
switch (response)

case "connection_failed":

// Block of code executes if the value of response is "connection_failed".

break;

case "connection_success":

// Block of code executes if the value of response is


"connection_success".

break;

case "connection_error":

// Block of code executes if the value of response is "connection_error".

break;

default:

// Block executes if none of the above conditions are met.

break;

Notice that there is a block labeled default:. This block of code will
execute when none of the other blocks match.

In each case statement, notice the break keyword. This causes control
to jump to the end of the switch after processing the block of code. If
you omit the break keyword, your code will not compile. If you want to
handle multiple cases with the same code segment, you can use a fall-
through setup similar to this sample code.

string response;
switch (response)

case "connection_success":

// Block of code executes if the value of response is


"connection_success".

break;

case "connection_failed":

case "connection_error":

// Block of code executes if the value of response is "connection_failed"

// or "connection_error;

break;

default:

// Block executes if none of the above conditions are met.

break;

If you are coming from another programming language, such as C, that


also uses the switch statement, you might notice that in the C#
language, you can use string values in your switch statements and
don't have to use integers or enumerated types. C# switch statements
support the following data types as expressions:

 sbyte

 byte

 short

 ushort
 int

 uint

 long

 ulong

 char

 string

 enumerations

Introducing Repetition
Bookmark this page

Introducing Repetition
Repetition is essentially the concept of doing something in a repeating
manner. In programming, you will typically use repetition to iterate
over items in a collection or to perform the same task over and over
again to produce the desired effect in your program.

Visual C# provides a number of standard constructs known as loops


that you can use to implement iteration logic. If you are coming from
other programming languages, you might recognize for loops, while
loops, and do loops. C# supports all three of these iteration
statements.

The for Loops


Bookmark this page

The for Loops


The for loop executes a block of code repeatedly until the specified
expression evaluates to false. You can define a for loop as follows.

for ([initializers]; [condition]; [iterator])

// code to repeat goes here

The [initializers] portion is used to initialize a value as a counter for


the loop. On each iteration, the loop checks that the value of the
counter is within the range to execute the for loop, specified in the
[condition] portion., and if so, execute the body of the loop. At then end
of each loop iteration, the [iterator] section is responsible for
incrementing the loop counter.

The following code example shows how to use a for loop to execute a
code block 10 times.

//for Loop

for (int i = 0 ; i < 10; i++)

// Code to execute.

In this example, i = 0; is the initializer, i < 10; is the condition, and i+


+ is the iterator.

For Each Loops


While a for loop is easy to use, it can present some challenges,
depending on the situation. As an example, consider iterating over a
collection or an array of values. You would need to know how many
elements are in the collection or array. In many cases you will know
this, but sometimes you may have collections or arrays that are
dynamic and are not sized at compile-time. If the size of the collection
or array changes during runtime, it might be a better option to use
a foreach loop.

The following code example shows how to use a foreach loop to iterate
a string array.

//foreach Loop

string[] names = new string[10];

// Process each name in the array.

foreach (string name in names)

// Code to execute.

C# handles determining how many items are in the array and will stop
executing the loop when the end is reached. The
use of foreach loops can help prevent index out of bounds errors on
arrays.

The while Loop


Bookmark this page

The while Loop


A while loop enables you to execute a block of code while a given
condition is true. For example, you can use a while loop to process
user input until the user indicates that they have no more data to
enter. The loop can continue to prompt the user until they decide to
end the interaction by entering a sentinel value. The sentinel value is
responsible for ending the loop.

The following code example shows how to use a while loop.

//while Loop

string response = PromptUser();

while (response != "Quit")

// Process the data.

response = PromptUser();

It's imperative to include the response = PromptUser(); inside the loop


braces. Failure to put this into the loop body will result in an infinite
loop because the sentinel value can never be changed.

You might also like