66
Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com

Csharp4 basics

Embed Size (px)

Citation preview

Page 1: Csharp4 basics

Abed El-Azeem Bukhari (MCPD,MCTS and MCP)el-bukhari.com

Page 2: Csharp4 basics

WhaT ’ s in This Lesson? ➤ Declaring variables ➤ Initialization and scope of variables ➤ Predefined C# data types ➤ Dictating the flow of execution within a C#

program using conditional statements, loops, and jump statements

➤ Enumerations ➤ Namespaces ➤ The Main() method ➤ Basic command - line C# compiler options ➤ Using System.Console to perform console I/O ➤ Using internal comments and documentation

features ➤ Preprocessor directives ➤ Guidelines and conventions for good

programming in C#

C# 4.0 Basics

Page 3: Csharp4 basics

using System;namespace Najah{ public class FirstClass { static void Main() { Console.WriteLine("Hello World."); Console.ReadLine(); return; } }}

Your first C# Program

Page 4: Csharp4 basics

int i = 10;

int x = 10, y =20; // x and y are both ints

int x = 10;bool y = true; // Creates a variable that stores true or falseint x = 10, bool y = true; // This won't compile!

Declaring Variables

Page 5: Csharp4 basics

C# has two methods for ensuring that variables are initialized before use:

1- Variables that are fields in a class or struct. (Default zeros)

2- Variables that are local to a method must be explicitly initialized

For example, you can’t do the following in C#:public static int Main(){int d;Console.WriteLine(d); // Can't do this! Need to initialize d before usereturn 0;}

// Compiler : Use of unassigned local variable 'd'

initialization of Variables

Page 6: Csharp4 basics

Consider the following statement:Something objSomething;

Instantiating a reference object in C# requires use of the new keyword. You create a reference as shown in theprevious example and then point the reference at an object allocated on the heap using the new keyword:

objSomething = new Something(); // This creates a Something on the heap

initialization of Variablesreference

Page 7: Csharp4 basics

Type inference makes use of the var keyword. The syntax for declaring the variable changes somewhat. The compiler “infers” what type the variable is by what the variable is initialized to. For example,

int someNumber = 0;

Becomes

var someNumber = 0;

Type inference

Page 8: Csharp4 basics

using System;namespace Najah{ class Program { static void Main(string[] args) { var name = “Ahmad"; var age = 25; var isHuman = true; Type nameType = name.GetType(); Type ageType = age.GetType(); Type isHumanType = isHuman.GetType(); Console.WriteLine("name is type " + nameType.ToString()); Console.WriteLine("age is type " + ageType.ToString()); Console.WriteLine(" isHuman is type " + isHumanType.ToString());}}}

var Examplename is type System.Stringage is type System.Int32isHuman is type System.Bool

Page 9: Csharp4 basics

➤ The variable must be initialized. Otherwise, the compiler doesn’t have anything to infer the type from.

➤ The initializer cannot be null.

➤ The initializer must be an expression.

➤ You can’t set the initializer to an object unless you create a new object in the initializer.

Some rules you need to follow

Page 10: Csharp4 basics

The scope of a variable is the region of code from which the variable can be accessed.You should follow this rules to determine Variable’s scope:1- Field and member variable : its scope is the whole class or struct.2- Local variable that is inside the parentheses : its scope from the declaring it to the closing of parentheses.3- Local variable that is inside for ,while and similar statements : its scope is in the parentheses of that statement.

For example, you can’t do this:int x = 20;// some more codeint x = 30;

Variable scope

Page 11: Csharp4 basics

using System;namespace DotNET.ILoveCSharp.Basics{ public class ScopeTest { public static int Main() { for (int i = 0; i < 10; i++) { Console.WriteLine(i); } // i goes out of scope here // We can declare a variable named i again, because // there's no other variable with that name in scope for (int i = 9; i >= 0; i--) { Console.WriteLine(i); } // i goes out of scope here. return 0; } }}

Variable scope cont.The important thing to note is that you declare the variable i twice in this code, within the same method. You can do this because i is declared in two separate loops, so each i variable is local To its own loop.

Page 12: Csharp4 basics

Here’s another example:public static int Main(){int j = 20;for (int i = 0; i < 10; i++){int j = 30; // Can't do this—j is still in scopeConsole.WriteLine(j + i);}return 0;}

Variable scope cont.

If you try to compile this, you’ll get an error like the following:ScopeTest.cs(12,15): error CS0136: A local variable named 'j' cannot be declared inthis scope because it would give a different meaning to 'j', which is already usedin a 'parent or current' scope to denote something else.

Page 13: Csharp4 basics

using System;namespace Najah{ class ScopeTest2 { static int j = 20; public static void Main() { int j = 30; Console.WriteLine(j);//30 Console.WriteLine(ScopeTest2.j);//20 return; } }}

scope Clashes for fields and local Variables

Page 14: Csharp4 basics

const int a = 100; // This value cannot be changed.

-Constants are static implicitly -You have to give a value to constant when you declare it.-You can’t change this value later.-You have to know that the value which given to constant variable must be in compile time so you can’t give it a value depending on another variables.(if you want to do so then you should use read-only fields which we will discuss later.)

Constants

Page 15: Csharp4 basics

➤ Value types : stores its value directly in memory, in an area known as the “stack”. For example, int which means that the following statement will result in two locations inmemory storing the value 20// i and j are both of type inti = 20;j = i;

Predefined data Types

Page 16: Csharp4 basics

➤ Reference types : stores a reference to the value in memory , in an area known as the “managed heap”.

Ex: Vector x, y;x = new Vector();x.Value = 30; // Value is a field defined in Vector classy = x;Console.WriteLine(y.Value); //30y.Value = 50;Console.WriteLine(x.Value);//50

Predefined data Types

Page 17: Csharp4 basics

➤ Reference types :If a variable is a reference, it is possible to indicate that it does not refer to any object by setting its valueto null :y = null;

Predefined data Types

Page 18: Csharp4 basics

Predefined Value Types

integer Types:

Page 19: Csharp4 basics

Predefined Value Types

integer Types cont.:

With .NET, a short is no longer quite so short; it is now 16 bits long. The int type is 32 bits long. Thelong type reserves 64 bits for values. All integer-type variables can be assigned values in decimal or in hex notation. The latter requires the 0x prefix:long x = 0x12ab;If there is any ambiguity about whether an integer is int, uint, long, or ulong, it will default to an int.To specify which of the other integer types the value should take, you can append one of the followingcharacters to the number:uint ui = 1234U;long l = 1234L;ulong ul = 1234UL;You can also use lowercase u and l, although the latter could be confused with the integer 1 (one).

Page 20: Csharp4 basics

Predefined Value Types

floating-Point Types:

The float data type is for smaller floating-point values, for which less precision is required. The double data type is bulkier than the float data type but offers twice the precision (15 digits).

If you hard-code a non-integer number (such as 12.3) in your code, the compiler will normally assume that you want the number interpreted as a double. If you want to specify that the value is a float, you appendthe character F (or f) to it:float f = 12.3F;

Page 21: Csharp4 basics

Predefined Value Types

Decimal Type:

To specify that your number is a decimal type rather than a double, float, or an integer, you can append the M (or m) character to the value, as shown in the following example:decimal d = 12.30M;

Page 22: Csharp4 basics

Predefined Value Types

Boolean Type:

You cannot implicitly convert bool values to and from integer values. If a variable (or a function return type) is declared as a bool, you can only use values of true and false. You will get an error if you try touse zero for false and a non-zero value for true.

Page 23: Csharp4 basics

Predefined Value Types

Character Type:

Literals of type char are signified by being enclosed in single quotation marks, for example ‘A’. If you try to enclose a character in double quotation marks, the compiler will treat this as a string and throwan error.

Page 24: Csharp4 basics

Predefined Value TypesCharacter Type cont.:

As well as representing chars as character literals, you can represent them with four-digit hexUnicode values (for example ‘\u0041’), as integer values with a cast (for example, (char)65), or ashexadecimal values (‘\x0041’). You can also represent them with an escape sequence, as shown in the following table.

Page 25: Csharp4 basics

Predefined reference Types

object and string,:

The object Type : a root type, we will study it later..!

The string type:

string str1 = "Hello ";string str2 = "World";string str3 = str1 + str2; // string concatenation

Page 26: Csharp4 basics

Predefined reference Types

The string type cont.:

using System;class StringExample{ public static int Main() { string s1 = "a string"; string s2 = s1; Console.WriteLine("s1 is " + s1); Console.WriteLine("s2 is " + s2); s1 = "another string"; Console.WriteLine("s1 is now " + s1); Console.WriteLine("s2 is now " + s2); return 0;}}

s1 is a strings2 is a strings1 is now another strings2 is now a string

Page 27: Csharp4 basics

Predefined reference Types cont.

The string type cont.:

string filepath = "C:\\DotNETClub\\First.cs";

string filepath = @"C:\ DotNETClub \First.cs";

string jabberwocky = @“’Hi for AllHow are you?.";

OUT' Hi for AllHow are you?.

Page 28: Csharp4 basics

The if statement

if (condition)statement(s)elsestatement(s)

//-------------------------------------------------------

bool isZero;if (i == 0){isZero = true;Console.WriteLine("i is Zero");}else{isZero = false;Console.WriteLine("i is Non-zero");}

Page 29: Csharp4 basics

The if statementclass MainEntryPoint{ static void Main(string[] args) { Console.WriteLine("Type in a string"); string input; input = Console.ReadLine(); if (input == "") { Console.WriteLine("You typed in an empty string."); } else if (input.Length < 5) { Console.WriteLine("The string had less than 5 characters."); } else if (input.Length < 10) { Console.WriteLine("The string had at least 5 but less than 10 Characters."); } Console.WriteLine("The string was " + input); }}

Page 30: Csharp4 basics

The switch statement

switch (integerA){case 1:Console.WriteLine("integerA =1");break;case 2:Console.WriteLine("integerA =2");break;case 3:Console.WriteLine("integerA =3");break;default:Console.WriteLine("integerA is not 1,2, or 3");break;}

Page 31: Csharp4 basics

The switch statement cont.

switch(country){case "America":CallAmericanOnlyMethod();goto case "Britain";case "France":language = "French";break;case "Britain":language = "English";break;}

Page 32: Csharp4 basics

The switch statement cont.

switch(country){case "au":case "uk":case "us":language = "English";break;case "at":case "de":language = "German";break;}

Page 33: Csharp4 basics

The switch statement cont.

// assume country is of type stringconst string palestine= “ps";const string jordan= “ps";switch(country){case palestine :case jordan : // This will cause a compilation error.language = “Arabic";break;}

Page 34: Csharp4 basics

Loops - For

for (initializer; condition; iterator)statement(s)

for (int i = 0; i < 100; i=i+1) // This is equivalent to // For i = 0 To 99 in VB.{Console.WriteLine(i);}

Page 35: Csharp4 basics

Loops – For cont.

// This loop iterates through rowsfor (int i = 0; i < 100; i+=10){// This loop iterates through columnsfor (int j = i; j < i + 10; j++){Console.Write(" " + j);}Console.WriteLine();}

The preceding sample results in this output:0 1 2 3 4 5 6 7 8 910 11 12 13 14 15 16 17 18 1920 21 22 23 24 25 26 27 28 2930 31 32 33 34 35 36 37 38 3940 41 42 43 44 45 46 47 48 4950 51 52 53 54 55 56 57 58 5960 61 62 63 64 65 66 67 68 6970 71 72 73 74 75 76 77 78 7980 81 82 83 84 85 86 87 88 8990 91 92 93 94 95 96 97 98 99

Page 36: Csharp4 basics

The while loop

while(condition)statement(s);

bool condition = false;while (!condition){// This loop spins until the condition is true.DoSomeWork();condition = CheckCondition(); // assume CheckCondition() returns a bool}

Page 37: Csharp4 basics

The do . . . while loop

bool condition;do{// This loop will at least execute once, even if Condition is false.MustBeCalledAtLeastOnce();condition = CheckCondition();} while (condition);

Page 38: Csharp4 basics

The foreach loop

if you assume that arrayOfInts is (unsurprisingly) an array of ints:

foreach (int temp in arrayOfInts){// temp++; // You Can’t Do this !Console.WriteLine(temp);}

Page 39: Csharp4 basics

jump statements- The goto statement

goto Label1;Console.WriteLine("This won't be executed");Label1:Console.WriteLine("Continuing execution from here");

In general, it certainly doesn’t conform to good object-oriented programming practice.

Page 40: Csharp4 basics

jump statements- The break statement

You have already met the break statement briefly — when you used it to exit from a case in a switchstatement. In fact, break can also be used to exit from for, foreach, while, or do...while loops. Controlwill switch to the statement immediately after the end of the loop.

Page 41: Csharp4 basics

jump statements- The continue statement

The continue statement is similar to break, and must also be used within a for, foreach, while, ordo...while loop. However, it exits only from the current iteration of the loop, meaning that execution willrestart at the beginning of the next iteration of the loop, rather than outside the loop altogether.

Page 42: Csharp4 basics

jump statements- The return statement

The return statement is used to exit a method of a class, returning control to the caller of the method. Ifthe method has a return type, return must return a value of this type; otherwise if the method returnsvoid, you should use return without an expression.

Page 43: Csharp4 basics

Enumerations

An enumeration is a user-defined integer type.

public enum TimeOfDay{Morning = 0,Afternoon = 1,Evening = 2}

Page 44: Csharp4 basics

Enumerations cont.class EnumExample{public static int Main(){WriteGreeting(TimeOfDay.Morning);return 0;}static void WriteGreeting(TimeOfDay timeOfDay){ switch(timeOfDay) { case TimeOfDay.Morning: Console.WriteLine("Good morning!"); break; case TimeOfDay.Afternoon: Console.WriteLine("Good afternoon!"); break; case TimeOfDay.Evening: Console.WriteLine("Good evening!"); break; default: Console.WriteLine("Hello!"); break;}}}

Page 45: Csharp4 basics

Enumerations cont.You can retrieve the string representation of an enum as in the following example, using the earlier

TimeOfDay enum:TimeOfDay time = TimeOfDay.Afternoon;

Console.WriteLine(time.ToString());

This will return the string Afternoon.

Alternatively, you can obtain an enum value from a string:

TimeOfDay time2 = (TimeOfDay) Enum.Parse(typeof(TimeOfDay), "afternoon", true);

Console.WriteLine((int)time2);

Page 46: Csharp4 basics

Namespacesnamespace CustomerPhoneBookApp{using System;public struct Subscriber{// Code for struct here...}}----------------------------------------------------namespace Najah{ namespace ILoveCSharp { namespace Basics { class NamespaceExample { // Code for the class here... } } }}

namespace Najah.ILoveCSharp.Basics{class NamespaceExample{// Code for the class here...}}

Page 47: Csharp4 basics

The using directive

using System;using Najah.ILoveCSharp;-----------------------------------------------------------------

using Najah.ILoveCSharp.OOP;using Najah.ILoveCSharp.Basics;namespace Najah.ILoveCSharp{class Test{public static int Main(){Basics.NamespaceExample nSEx = new Basics.NamespaceExample();// do something with the nSEx variable.return 0;}}|

Page 48: Csharp4 basics

namespace aliasesusing alias = NamespaceName;------------------------------------using System;using Introduction = Najah.ILoveCSharp.Basics;class Test{public static int Main(){Introduction::NamespaceExample NSEx = new Introduction::NamespaceExample();Console.WriteLine(NSEx.GetNamespace());return 0;}}namespace Najah.ILoveCSharp.Basics{class NamespaceExample{public string GetNamespace(){return this.GetType().Namespace;}}}

Page 49: Csharp4 basics

multiple Main() methodsusing System;

namespace Najah{ class Client { public static int Main() { MathExample.Main(); return 0; } } class MathExample { static int Add(int x, int y) { return x + y; } public static int Main(){ int i = Add(5,10); Console.WriteLine(i); return 0;}}}

csc DoubleMain.csMicrosoft (R) Visual C# 2010 Compiler version 4.0.20506.1Copyright (C) Microsoft Corporation. All rights reserved.DoubleMain.cs(7,25): error CS0017: Program'DoubleMain.exe' has more than one entry point defined:‘Najah.Client.Main()'. Compile with /main to specify the type thatcontains the entry point.DoubleMain.cs(21,25): error CS0017: Program'DoubleMain.exe' has more than one entry point defined:‘Najah.MathExample.Main()'. Compile with /main to specify the type thatcontains the entry point.

csc DoubleMain.cs /main:Najah.MathExample

Page 50: Csharp4 basics

Passing arguments to Main()

using System;namespace Najah{ class ArgsExample { public static int Main(string[] args) { for (int i = 0; i < args.Length; i++) { Console.WriteLine(args[i]); } return 0; } }} ArgsExample /a /b /c

/a/b/c

Page 51: Csharp4 basics

more on Compiling C# files

The class librarynamespace Najah{ public class MathLib { public int Add(int x, int y) { return x + y; } }} csc /t:library MathLibrary.cs

Page 52: Csharp4 basics

more on Compiling C# files

using System;namespace Najah { class Client { public static void Main() { MathLib mathObj = new MathLib(); Console.WriteLine(mathObj.Add(7,8)); } } }

csc MathClient.cs /r:MathLibrary.dll

Page 53: Csharp4 basics

Console I/O

➤ Console.Write() — Writes the specified value to the console window. ➤ Console.WriteLine() — This does the same, but adds a newline

character at the end of the output.

string s = Console.ReadLine();Console.WriteLine(s);

int i = 10;int j = 20;Console.WriteLine("{0} plus {1} equals {2}", i, j, i + j);

10 plus 20 equals 30

Page 54: Csharp4 basics

Console I/O cont.

decimal i = 940.23m;decimal j = 73.7m;Console.WriteLine(" {0,9:C2}\n+{1,9:C2}\n —— \n {2,9:C2}", i, j, i + j);The output of this in U.S. currency is: $940.23+ $73.70 ———— $1,013.93

double d = 0.234;Console.WriteLine("{0:#.00}", d);//.23

Page 55: Csharp4 basics

internal Comments within the source files

// This is a singleline comment/* This commentspans multiple lines. */

Console.WriteLine(/* Here's a comment! */ "This will compile.");

DoSomething(Width, /*Height*/ 100);

string s = "/* This is just a normal string .*/";

Page 56: Csharp4 basics

Xml documentation

Page 57: Csharp4 basics

Xml documentation cont.

namespace Najah{///<summary>/// Najah.Math class./// Provides a method to add two integers.///</summary>public class MathLib{///<summary>/// The Add method allows us to add two integers.///</summary>///<returns>Result of the addition (int)</returns>///<param name="x">First number to add</param>///<param name="y">Second number to add</param>public int Add(int x, int y){return x + y;}}}

Page 58: Csharp4 basics

Xml documentation cont.

csc /t:library /doc:MathLibrary.xml MathLibrary.cs

<?xml version="1.0"?><doc><assembly><name>MathLibrary</name></assembly><members><member name="T:Najah.MathLibrary"><summary>Najah.MathLibrary class.Provides a method to add two integers.</summary></member><member name="M:Wrox.MathLibrary.Add(System.Int32,System.Int32)">< summary >The Add method allows us to add two integers.< /summary >< returns > Result of the addition (int) < /returns >< param name="x" > First number to add < /param >< param name="y" > Second number to add < /param >< /member >< /members >< /doc >

Page 59: Csharp4 basics

The C# PreProcessor directives

#define and #undef

#define is used like this:#define DEBUG

#undef does the opposite, and removes the defi nition of a symbol:#undef DEBUG

#if, #elif, #else, and #endifint DoSomeWork(double x){// do something#if DEBUGConsole.WriteLine("x is " + x);#endif}

Page 60: Csharp4 basics

The C# PreProcessor directives cont.#define DOTNET

#define ILoveCSharp// further on in the file#if DOTNET// do something#if ILoveCSharp// some code that is only relevant to dotnet// running on ILoveCSharp#endif#elif ILoveVB// do something else#else// code for the leaner version#endif

#if and #elif support a limited range of logical operators too, using the operators ! , == , != , and || . Asymbol is considered to be true if it exists and false if it doesn ’ t. For example:#if ILoveCSharp & & (DOTNET ==false) // if ILoveCSharp is defined but DOTNET isn't

Page 61: Csharp4 basics

The C# PreProcessor directives cont.#warning and #error

#if DEBUG & & RELEASE#error "You've defined DEBUG and RELEASE simultaneously!"#endif#warning "Don't forget to remove this line before the boss tests the code!"Console.WriteLine("*I hate this job.*");

#region Member Field Declarationsint x;double d;Currency balance;#endregion

#region and #endregion

Page 62: Csharp4 basics

The C# PreProcessor directives cont.

#line

#line 164 "Core.cs" // We happen to know this is line 164 in the file// Core.cs, before the intermediate// package mangles it.// later on#line default // restores default line numbering

#pragma warning disable 169public class MyClass{int neverUsedField;}#pragma warning restore 169

#pragma

Page 63: Csharp4 basics

C# Programming guidelines

rules for identifiers

- They must begin with a letter or underscore, although they can contain numeric characters.➤- You can’t use C# keywords as identifiers.

Page 64: Csharp4 basics

C# Programming guidelines cont.

Page 65: Csharp4 basics

C# Programming guidelines cont.Names:

➤ Name ➤ Überfluß ➤ _Identifier ➤ \u005fIdentifier

Page 66: Csharp4 basics

Thanks For Attending

Abed El-Azeem Bukhari (MCPD,MCTS and MCP)

el-bukhari.com