session 1 c# basics

45
Session 1 C# Basics

Upload: britton-greene

Post on 18-Jan-2018

246 views

Category:

Documents


0 download

DESCRIPTION

Objectives Explain the need for C# Discuss flow of control of a C# program List the fundamental data types in C# Discuss the concepts of Boxing and UnBoxing Discuss Structures and enumerators Discuss a simple C# program

TRANSCRIPT

Page 1: Session 1 C# Basics

Session 1

C# Basics

Page 2: Session 1 C# Basics

C# Simplified / Session 1 / 2 of 45

Objectives Explain the need for C# Discuss flow of control of a C# program List the fundamental data types in C# Discuss the concepts of Boxing and

UnBoxing Discuss Structures and enumerators Discuss a simple C# program

Page 3: Session 1 C# Basics

C# Simplified / Session 1 / 3 of 45

Microsoft .NET New platform for developing

windows & web applications Supports more than 20 languages Revolutionizes facilities available

for Windows programming

Page 4: Session 1 C# Basics

C# Simplified / Session 1 / 4 of 45

Introduction to C# C# compiler is the most efficient

compiler in the .NET family Provides native support for COM

(Component Object Model) Enhances developer productivity and

increases safety, by enforcing strict type checking

Allows restricted use of native pointers

Page 5: Session 1 C# Basics

C# Simplified / Session 1 / 5 of 45

C# Program FlowA simple C# program –/* This is the Hello world Program in C# */

using System;

class HelloWorldDemo { public static void Main() { Console.WriteLine (“This is the Hello World

program”); } }

Page 6: Session 1 C# Basics

C# Simplified / Session 1 / 6 of 45

C# ConstructsVariables in C# are declared as follows

AccessModifier DataType VariablePublic

PrivateProtected

int

stringfloat

Page 7: Session 1 C# Basics

C# Simplified / Session 1 / 7 of 45

C# Constructs – Contd… To use a keyword as a variable name, prefix the variable name with a ‘@’ symbol.

using System;class VariableDemo{

public static void Main(){

string @string; @string = ”string is a keyword but used as a

variable name in this example”; Console.WriteLine (@string);

}}

Page 8: Session 1 C# Basics

C# Simplified / Session 1 / 8 of 45

C# Constructs – Contd…using System;class DefaultValDemo{public static void Main() { int[] array1 = new int[5]; Console.WriteLine(“10 multiplied by default value of second array element is {0}“ , 10 * array1[2]); }}

Page 9: Session 1 C# Basics

C# Simplified / Session 1 / 9 of 45

C# Data TypesC# Data

typeDescription Example

object Base data type for all other types. object o = null; string Declares a variable that can store string

values string s = “hello”;

int Declares a variable that can store integer values.

int val = 12;

byte Declares a variable that can store byte integer values.

byte val = 12;

float Declares a variable, which can store real number values that have integer and decimals parts

float val = 1.23F;

bool Declares a variable, which can store real number values that have integer and decimals parts

bool val1 = true;bool val2 = false;

char Declares a variable, which can store char values.

char val = 'h';

Page 10: Session 1 C# Basics

C# Simplified / Session 1 / 10 of 45

Default ValuesDefault values of the common data types:

Type Default ValueNumeric (int,float,short)

0

Bool FalseChar ‘\0’Enum 0

Page 11: Session 1 C# Basics

C# Simplified / Session 1 / 11 of 45

Input / Output In C# Uses methods of the Console class

in the System namespace

The most widely used methods are –

Console.ReadLine()

Console.WriteLine()

Page 12: Session 1 C# Basics

C# Simplified / Session 1 / 12 of 45

The highlighted line uses the placeholder {0} where the value of the specified variables (result and number) will be

substituted and displayed.

Input / Output In C# - Contd…using System;class TestDefaultValues{ static void Main() { int number, result; number=5; result=100 * number; Console.WriteLine (“Result is {0} when 100

is multiplied by number {1}”, result, number); }}

Page 13: Session 1 C# Basics

C# Simplified / Session 1 / 13 of 45

Input / Output In C# - Contd…Input / Output In C# - Contd…using System;class InputStringDemo{ public static void Main() { string input; input = Console.ReadLine(); Console.WriteLine (“The input string was :{0}”, input); }}

Page 14: Session 1 C# Basics

C# Simplified / Session 1 / 14 of 45

The if construct Used for performing conditional branching Syntax -

The expression should always evaluate to an expression of Boolean type

if (expression){ //One or more statements to be executed if the expression evaluates to true}[else{ //One or more statements to be executed if the expression evaluates to false}]

Page 15: Session 1 C# Basics

C# Simplified / Session 1 / 15 of 45

The above piece of code will display an error message -

Selection Statement

Error CS0029 : Cannot implicitly convert type 'int' to 'bool'

string str = ”hello”;if (str)

System.Console.WriteLine (“The value is True”);if (str == “hello”)

System.Console.WriteLine (“The Value is True”);

Page 16: Session 1 C# Basics

C# Simplified / Session 1 / 16 of 45

The switch StatementSyntax

switch(variable){

case value://Statements break;

case value://Statements break;

default://Statements

break;}

Page 17: Session 1 C# Basics

C# Simplified / Session 1 / 17 of 45

The switch Statement – Contd…

switch(weekday){ case 1:

Console.WriteLine (“You have selected Monday”);break;

case 2:Console.WriteLine (“You have selected Tuesday”);break;

default:Console.WriteLine (“Sunday is the Default choice!”);break;

}

Page 18: Session 1 C# Basics

C# Simplified / Session 1 / 18 of 45

Iteration Constructs Perform a certain set of instructions for

a certain number of times or while a specific condition is true

Types of iteration constructs – The While Loop The Do Loop The For Loop The foreach Loop

Page 19: Session 1 C# Basics

C# Simplified / Session 1 / 19 of 45

The while loop iterates through the specified statements till the condition specified is true

Syntax –

The while loop

The break statement - to break out of the loop at anytime

The continue statement - to skip the current iteration and begin with the next iteration

Page 20: Session 1 C# Basics

C# Simplified / Session 1 / 20 of 45

The do loopSyntax -

Page 21: Session 1 C# Basics

C# Simplified / Session 1 / 21 of 45

The for loopSyntax -

Page 22: Session 1 C# Basics

C# Simplified / Session 1 / 22 of 45

The foreach loop (1) The foreach loop is used to iterate

through a collection or an array Syntax -

Page 23: Session 1 C# Basics

C# Simplified / Session 1 / 23 of 45

The foreach loop – Contd…using System;public class ForEachDemo{ static void Main (String[] args) { int index; String[] array1=new String[3]; for (index=0;index<3;index++) { array1[index]=args [index]; } foreach (String strName in array1) { Console.WriteLine (strName); } }}

Page 24: Session 1 C# Basics

C# Simplified / Session 1 / 24 of 45

Fundamental Types Of C# C# divides data types into two

fundamental categories

Value Types- int, char , and structures

Reference Types- classes, interfaces, arrays and strings

Page 25: Session 1 C# Basics

C# Simplified / Session 1 / 25 of 45

Just hold a value in memory Are stored in a stack

Contains the address of the object in the heap = null means that no object has been referenced

Fundamental Types Of C# - Contd…

Value Types

Reference Types

Page 26: Session 1 C# Basics

C# Simplified / Session 1 / 26 of 45

Value TypesValue Typesusing System;class DataTypeTest{ public static void Main()   {     int variableVal = 100;     funcTest(variableVal); Console.WriteLine(“This value of the variable is {0}",variableVal);    }   static void funcTest (int variableVal)   { int tempVar = 10;       variableVal = tempVar*20;    }}

Page 27: Session 1 C# Basics

C# Simplified / Session 1 / 27 of 45

Reference Typesusing System;class DataTypeTest{ public int variableVal;}class DataTypeTestRef{ static void Main() { DataTypeTest dataTest = new DataTypeTest(); dataTest.variableVal = 100; funcDataTypeTest(dataTest); Console.WriteLine (dataTest.variableVal); }

Page 28: Session 1 C# Basics

C# Simplified / Session 1 / 28 of 45

Reference Types - Contdstatic void funcDataTypeTest(DataTypeTest dataTest) { int tempVar = 10;      dataTest.variableVal = tempVar*20; }}

Page 29: Session 1 C# Basics

C# Simplified / Session 1 / 29 of 45

Value types vs. Reference types

Value Reference

Variable Holds Actual Value ReferenceAllocated Inline (Stack) Heap

Default Value Zero NullParameter to

functionsCopy Value Copy

Reference

Page 30: Session 1 C# Basics

C# Simplified / Session 1 / 30 of 45

Boxing & Unboxing

Boxing is conversion of a value type into a reference type

Unboxing is the conversion of a reference type into a value type

Page 31: Session 1 C# Basics

C# Simplified / Session 1 / 31 of 45

Boxing & Unboxing – Contd…...class BoxEx{ int objsTaker(object objectX) {

//objsTaker takes an object//and processes it here

} object objsConverter() {

//objsConverter does the processing //and returns an object }}...//Implementation of codeint variable1;variable1 = 5;BoxEx boxVar = new BoxEx();boxVar.objsTaker(variable1); //line 1int convertVar = (int) boxVar.objsConverter(); //line 2...

Page 32: Session 1 C# Basics

C# Simplified / Session 1 / 32 of 45

Data Types In C# C# provides us with a Unified Type System All data types in C#, are derived from just one

class, the object classusing System;class ObjectProff{public static void Main()

{string objectVal;objectVal = 7.ToString();Console.WriteLine (“The value now is

”+objectVal);}

}

Page 33: Session 1 C# Basics

C# Simplified / Session 1 / 33 of 45

Static Members Members are not associated with

any particular object or the class Only one instance of this member

is possible…static int staticMem;…static int instanceCount(){

//instanceCount Implementation}…

Page 34: Session 1 C# Basics

C# Simplified / Session 1 / 34 of 45

DataType[number of elements] ArrayName;

int[6] array1;

Arrays A group of values of similar data type Belong to the reference type and hence

are stored on the heap The declaration of arrays in C# follow

the syntax given below -

Page 35: Session 1 C# Basics

C# Simplified / Session 1 / 35 of 45

Structures Custom data Types Can have methods

defined within them Cannot implement

inheritance Represent Value types

…struct structEx{ public int structDataMember; public void structMethod1() {

//structMethod1 Implementation }}…

Page 36: Session 1 C# Basics

C# Simplified / Session 1 / 36 of 45

Enumeratorspublic class Holiday{ public enum WeekDays {

Monday,Tuesday,Wednesday,Thursday,Friday

} public void GetWeekDays (String EmpName, WeekDays DayOff) { //Process WeekDays } static void Main() { Holiday myHoliday = new Holiday(); myHoliday.GetWeekDays (“Richie”,

Holiday.WeekDays.Wednesday); }}

Page 37: Session 1 C# Basics

C# Simplified / Session 1 / 37 of 45

Enumerators – Contd… Enumerators in C# have numbers associated with the values By default, the first element of the enum is assigned a value

of 0 and is incremented for each subsequent enum element The default value can be overridden during initialization

public enum WeekDays{

Monday=1,Tuesday=2,Wednesday=3,Thursday=4,Friday=5

}

Page 38: Session 1 C# Basics

C# Simplified / Session 1 / 38 of 45

Compiling and Executing C# Program Click 'Start Programs Microsoft

Visual Studio.Net 2003'

Start Page screen showing recently used projects is displayed on the screen

Page 39: Session 1 C# Basics

C# Simplified / Session 1 / 39 of 45

Compiling and Executing C# Program – Contd…

Page 40: Session 1 C# Basics

C# Simplified / Session 1 / 40 of 45

Compiling and Executing C# Program – Contd… Click File New Project to start a new project Select 'Visual C# Projects' from the list on the

right hand side and 'Console Application' from the list on the left hand side

Type the name of the project in the 'Name' section as Example 1.

In the Solution Explorer rename ConsoleApplication1 to Chapter1

Rename the project to Example1 and Class1.cs to HelloWorldDemo.cs

Page 41: Session 1 C# Basics

C# Simplified / Session 1 / 41 of 45

Compiling and Executing C# Program – Contd…

Page 42: Session 1 C# Basics

C# Simplified / Session 1 / 42 of 45

Compiling and Executing C# Program – Contd… Save the file and Select Build

Build Solution option to build the solution

Select Start without Debugging option from the Debug menu to execute the application

Page 43: Session 1 C# Basics

C# Simplified / Session 1 / 43 of 45

Compiling and Executing C# Program – Contd… Another method to compile and execute a

program is using notepad and DOS prompt Step 1 – Type your code in Notepad Step 2 – Save the file with a .cs extension Step 3 – Switch to DOS prompt and type

the following command

csc <filename>.cs To run the C# file, type the name of the

file without the extension

Page 44: Session 1 C# Basics

C# Simplified / Session 1 / 44 of 45

Summary C# is an object oriented language with many powerful

features and is an integral part of the .Net platform Variables in C# are declared in the following way

AccessModifier DataType VariableName; C# provides the if and switch…case constructs to

perform operations based on the value of an expression. C# provides the following types of iteration constructs,

while loop do loop for loop foreach loop

Page 45: Session 1 C# Basics

C# Simplified / Session 1 / 45 of 45

Summary In C#, the data types are divided into two fundamental

categories namely value types and reference types.

Boxing is the conversion of a value type into a reference type while Unboxing refers to converting a reference type into a value type.

Structs in C# can have methods defined within them, and represent Value types.

Enums (short for Enumerators) are a set of named numeric constants.

C# programs can be written using the Visual Studio .NET IDE as well as Notepad