SlideShare a Scribd company logo
1 of 66
Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com
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
using System; namespace Najah { public class FirstClass { static void Main() { Console.WriteLine("Hello World."); Console.ReadLine(); return; } } } Your first C# Program
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 false int x = 10, bool  y = true; //  This won't compile! Declaring Variables
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 use return 0; } // Compiler  :  Use of unassigned local variable 'd ' initialization of Variables
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 the previous 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 Variables reference
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
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 Example name is type System.String age is type System.Int32 isHuman  is type System.Bool
➤  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
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 code int x = 30; Variable scope
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.
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 scope Console.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 in this scope because it would give a different meaning to 'j', which is already used in a 'parent or current' scope to denote something else.
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
[object Object],[object Object],[object Object],[object Object],[object Object],Constants
➤  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 in memory storing the value 20 //  i and j are both of type int i = 20; j = i; Predefined data Types
➤  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 class y = x; Console.WriteLine( y .Value); //30 y.Value = 50; Console.WriteLine( x .Value);//50 Predefined data Types
➤  Reference types  : If a variable is a reference, it is possible to indicate that it does not refer to any object by setting its value to null : y = null; Predefined data Types
Predefined Value Types integer Types:
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. The long 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 =  0x 12ab; 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 following characters 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).
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 append the character F (or f) to it: float f = 12.3F;
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;
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 to use zero for false and a non-zero value for true.
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 throw an error.
Predefined Value Types Character  Type cont.: As well as representing chars as character literals,  you can represent them with four-digit hex Unicode values (for example ‘0041’),  as integer values with a cast (for example, (char)65), or as hexadecimal values (‘0041’). You can also represent them with an escape sequence,  as shown in the following table.
Predefined reference Types object and string, : The object Type :  a root type, we will study it later..! The string type: string str1 = &quot;Hello &quot;; string str2 = &quot;World&quot;; string str3 = str1 + str2; // string concatenation
Predefined reference Types The string type cont.: using System; class StringExample { public static int Main() { string s1 = &quot;a string&quot;; string s2 = s1; Console.WriteLine(&quot;s1 is &quot; + s1); Console.WriteLine(&quot;s2 is &quot; + s2); s1 = &quot;another string&quot;; Console.WriteLine(&quot;s1 is now &quot; + s1); Console.WriteLine(&quot;s2 is now &quot; + s2); return 0; } } s1 is a string s2 is a string s1 is now another string s2 is now a string
Predefined reference Types cont. The string type cont.: string filepath = &quot;C:DotNETClubFirst.cs&quot;; string filepath = @&quot;C:DotNETClub irst.cs&quot;; string jabberwocky = @“’Hi for All How are you?.&quot;; OUT ' Hi for All How are you?.
The if statement if (condition) statement(s) else statement(s) //------------------------------------------------------- bool isZero; if (i == 0) { isZero = true; Console.WriteLine(&quot;i is Zero&quot;); } else { isZero = false; Console.WriteLine(&quot;i is Non-zero&quot;); }
The if statement class MainEntryPoint { static void Main(string[] args) { Console.WriteLine(&quot;Type in a string&quot;); string input; input = Console.ReadLine(); if (input == &quot;&quot;) { Console.WriteLine(&quot;You typed in an empty string.&quot;); } else if (input.Length < 5) { Console.WriteLine(&quot;The string had less than 5 characters.&quot;); } else if (input.Length < 10) { Console.WriteLine(&quot;The string had at least 5 but less than 10 Characters.&quot;); } Console.WriteLine(&quot;The string was &quot; + input); } }
The switch statement switch (integerA) { case 1: Console.WriteLine(&quot;integerA =1&quot;); break; case 2: Console.WriteLine(&quot;integerA =2&quot;); break; case 3: Console.WriteLine(&quot;integerA =3&quot;); break; default: Console.WriteLine(&quot;integerA is not 1,2, or 3&quot;); break; }
The switch statement cont. switch(country) { case &quot;America&quot;: CallAmericanOnlyMethod(); goto case &quot;Britain&quot;; case &quot;France&quot;: language = &quot;French&quot;; break; case &quot;Britain&quot;: language = &quot;English&quot;; break; }
The switch statement cont. switch(country) { case &quot;au&quot;: case &quot;uk&quot;: case &quot;us&quot;: language = &quot;English&quot;; break; case &quot;at&quot;: case &quot;de&quot;: language = &quot;German&quot;; break; }
The switch statement cont. // assume country is of type string const string  palestine= “ps&quot;; const string  jordan= “ps&quot;; switch(country) { case palestine : case jordan : // This will cause a compilation error. language = “Arabic&quot;; break; }
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); }
Loops – For  cont. // This loop iterates through rows for (int i = 0; i < 100; i+=10) { // This loop iterates through columns for (int j = i; j < i + 10; j++) { Console.Write(&quot; &quot; + j); } Console.WriteLine(); } The preceding sample results in this output: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
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 }
The do . . . while loop bool condition; do { // This loop will at least execute once, even if Condition is false. MustBeCalledAtLeastOnce(); condition = CheckCondition(); } while (condition);
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); }
jump statements-  The goto statement goto Label1; Console.WriteLine(&quot;This won't be executed&quot;); Label1: Console.WriteLine(&quot;Continuing execution from here&quot;); In general, it certainly doesn’t conform to good object-oriented programming practice.
jump statements-  The break statement You have already met the break statement briefly — when you used it to exit from a case in a switch statement. In fact, break can also be used to exit from for, foreach, while, or do...while loops. Control will switch to the statement immediately after the end of the loop.
jump statements-  The continue statement The continue statement is similar to break, and must also be used within a for, foreach, while, or do...while loop. However, it exits only from the current iteration of the loop, meaning that execution will restart at the beginning of the next iteration of the loop, rather than outside the loop altogether.
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. If the method has a return type, return must return a value of this type; otherwise if the method returns void, you should use return without an expression.
Enumerations An  enumeration is a user-defined integer type. public enum TimeOfDay { Morning = 0, Afternoon = 1, Evening = 2 }
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(&quot;Good morning!&quot;); break; case TimeOfDay.Afternoon: Console.WriteLine(&quot;Good afternoon!&quot;); break; case TimeOfDay.Evening: Console.WriteLine(&quot;Good evening!&quot;); break; default: Console.WriteLine(&quot;Hello!&quot;);  break; }}}
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), &quot;afternoon&quot;, true); Console.WriteLine((int)time2);
Namespaces namespace 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... } }
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; } } |
namespace aliases using 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; }}}
multiple Main() methods using 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.cs Microsoft (R) Visual C# 2010 Compiler version 4.0.20506.1 Copyright (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 that contains 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 that contains the entry point. csc DoubleMain.cs /main:Najah.MathExample
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
more on Compiling C# files The class library namespace Najah { public class MathLib { public int Add(int x, int y) { return x + y; } } } csc /t:library MathLibrary.cs
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
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(&quot;{0} plus {1} equals {2}&quot;, i, j, i + j); 10 plus 20 equals 30
Console I/O cont. decimal i = 940.23m; decimal j = 73.7m; Console.WriteLine(&quot; {0,9:C2}+{1,9:C2} ——  {2,9:C2}&quot;, 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(&quot;{0:#.00}&quot;, d);//.23
internal Comments within the source files // This is a singleline comment /* This comment spans multiple lines. */ Console.WriteLine( /* Here's a comment! */  &quot;This will compile.&quot;); DoSomething(Width,  /*Height*/  100); string s = &quot;/* This is just a normal string .*/&quot;;
Xml documentation
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=&quot;x&quot;>First number to add</param> ///<param name=&quot;y&quot;>Second number to add</param> public int Add(int x, int y) { return x + y; } } }
Xml documentation cont. csc /t:library /doc:MathLibrary.xml MathLibrary.cs <?xml version=&quot;1.0&quot;?> <doc> <assembly> <name>MathLibrary</name> </assembly> <members> <member name=&quot;T:Najah.MathLibrary&quot;> <summary> Najah.MathLibrary class. Provides a method to add two integers. </summary> </member> <member name=&quot;M:Wrox.MathLibrary.Add(System.Int32,System.Int32)&quot;> < summary > The Add method allows us to add two integers. < /summary > < returns > Result of the addition (int) < /returns > < param name=&quot;x&quot; > First number to add < /param > < param name=&quot;y&quot; > Second number to add < /param > < /member > < /members > < /doc >
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 #endif int DoSomeWork(double x) { // do something #if  DEBUG Console.WriteLine(&quot;x is &quot; + x); #endif }
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 || . A symbol 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
The C# PreProcessor directives cont. #warning and #error #if DEBUG & & RELEASE #error &quot; You've defined DEBUG and RELEASE simultaneously !&quot; #endif #warning &quot; Don't forget to remove this line before the boss tests the code!&quot; Console.WriteLine(&quot;*I hate this job.*&quot;); #region Member Field Declarations int x; double d; Currency balance; #endregion #region and #endregion
The C# PreProcessor directives cont. #line #line 164 &quot;Core.cs&quot; // 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  169 public class MyClass { int neverUsedField; } #pragma warning restore  169 #pragma
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.
C# Programming guidelines cont.
C# Programming guidelines cont. Names: ➤  Name ➤  Überfluß ➤  _Identifier ➤  005fIdentifier
Thanks For Attending Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com

More Related Content

What's hot

C presentation book
C presentation bookC presentation book
C presentation bookkrunal1210
 
datatypes and variables in c language
 datatypes and variables in c language datatypes and variables in c language
datatypes and variables in c languageRai University
 
Basic C Programming language
Basic C Programming languageBasic C Programming language
Basic C Programming languageAbhishek Soni
 
Variables and data types in C++
Variables and data types in C++Variables and data types in C++
Variables and data types in C++Ameer Khan
 
Data Types and Variables In C Programming
Data Types and Variables In C ProgrammingData Types and Variables In C Programming
Data Types and Variables In C ProgrammingKamal Acharya
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingSherwin Banaag Sapin
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageRakesh Roshan
 
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++  Langauage Training in Ambala ! BATRA COMPUTER CENTREC++  Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTREjatin batra
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming CourseDennis Chang
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 FocJAYA
 

What's hot (20)

Tokens in C++
Tokens in C++Tokens in C++
Tokens in C++
 
C presentation book
C presentation bookC presentation book
C presentation book
 
datatypes and variables in c language
 datatypes and variables in c language datatypes and variables in c language
datatypes and variables in c language
 
C material
C materialC material
C material
 
Data type in c
Data type in cData type in c
Data type in c
 
Declaration of variables
Declaration of variablesDeclaration of variables
Declaration of variables
 
Basic C Programming language
Basic C Programming languageBasic C Programming language
Basic C Programming language
 
Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
 
Variables and data types in C++
Variables and data types in C++Variables and data types in C++
Variables and data types in C++
 
Data Types and Variables In C Programming
Data Types and Variables In C ProgrammingData Types and Variables In C Programming
Data Types and Variables In C Programming
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# Programming
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C language
 
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++  Langauage Training in Ambala ! BATRA COMPUTER CENTREC++  Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
C++ Basics
C++ BasicsC++ Basics
C++ Basics
 
C programming notes
C programming notesC programming notes
C programming notes
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Pc module1
Pc module1Pc module1
Pc module1
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
 

Viewers also liked

CIS110 Computer Programming Design Chapter (4)
CIS110 Computer Programming Design Chapter  (4)CIS110 Computer Programming Design Chapter  (4)
CIS110 Computer Programming Design Chapter (4)Dr. Ahmed Al Zaidy
 
CIS110 Computer Programming Design Chapter (5)
CIS110 Computer Programming Design Chapter  (5)CIS110 Computer Programming Design Chapter  (5)
CIS110 Computer Programming Design Chapter (5)Dr. Ahmed Al Zaidy
 
Introduction to Programming
Introduction to ProgrammingIntroduction to Programming
Introduction to ProgrammingChaffey College
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsAbed Bukhari
 
Secure mvc application saineshwar
Secure mvc application   saineshwarSecure mvc application   saineshwar
Secure mvc application saineshwarSaineshwar bageri
 
Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuplesAbed Bukhari
 
Free MVC project to learn for beginners.
Free MVC project to learn for beginners.Free MVC project to learn for beginners.
Free MVC project to learn for beginners.Saineshwar bageri
 
Logic Formulation 3
Logic Formulation 3Logic Formulation 3
Logic Formulation 3deathful
 
Introduction to .NET Core & ASP.NET Core MVC
Introduction to .NET Core & ASP.NET Core MVCIntroduction to .NET Core & ASP.NET Core MVC
Introduction to .NET Core & ASP.NET Core MVCSaineshwar bageri
 
Introduction to C# 6.0 and 7.0
Introduction to C# 6.0 and 7.0Introduction to C# 6.0 and 7.0
Introduction to C# 6.0 and 7.0Saineshwar bageri
 
Komunikasyon
KomunikasyonKomunikasyon
Komunikasyondeathful
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programmingparamalways
 
Minto pyramid
Minto pyramidMinto pyramid
Minto pyramidshachihp
 

Viewers also liked (16)

CIS110 Computer Programming Design Chapter (4)
CIS110 Computer Programming Design Chapter  (4)CIS110 Computer Programming Design Chapter  (4)
CIS110 Computer Programming Design Chapter (4)
 
CIS110 Computer Programming Design Chapter (5)
CIS110 Computer Programming Design Chapter  (5)CIS110 Computer Programming Design Chapter  (5)
CIS110 Computer Programming Design Chapter (5)
 
Introduction to Programming
Introduction to ProgrammingIntroduction to Programming
Introduction to Programming
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_events
 
Secure mvc application saineshwar
Secure mvc application   saineshwarSecure mvc application   saineshwar
Secure mvc application saineshwar
 
Whats New In C# 3.0
Whats New In C# 3.0Whats New In C# 3.0
Whats New In C# 3.0
 
Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuples
 
Free MVC project to learn for beginners.
Free MVC project to learn for beginners.Free MVC project to learn for beginners.
Free MVC project to learn for beginners.
 
C# language
C# languageC# language
C# language
 
Logic Formulation 3
Logic Formulation 3Logic Formulation 3
Logic Formulation 3
 
C# 3.5 Features
C# 3.5 FeaturesC# 3.5 Features
C# 3.5 Features
 
Introduction to .NET Core & ASP.NET Core MVC
Introduction to .NET Core & ASP.NET Core MVCIntroduction to .NET Core & ASP.NET Core MVC
Introduction to .NET Core & ASP.NET Core MVC
 
Introduction to C# 6.0 and 7.0
Introduction to C# 6.0 and 7.0Introduction to C# 6.0 and 7.0
Introduction to C# 6.0 and 7.0
 
Komunikasyon
KomunikasyonKomunikasyon
Komunikasyon
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
 
Minto pyramid
Minto pyramidMinto pyramid
Minto pyramid
 

Similar to Csharp4 basics

Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingRasan Samarasinghe
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1Hossein Zahed
 
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# programMAHESHV559910
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp PresentationVishwa Mohan
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)SURBHI SAROHA
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_castsAbed Bukhari
 
Object Oriented Programming with C++
Object Oriented Programming with C++Object Oriented Programming with C++
Object Oriented Programming with C++Rokonuzzaman Rony
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2Warui Maina
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
 
Programming in C - interview questions.pdf
Programming in C - interview questions.pdfProgramming in C - interview questions.pdf
Programming in C - interview questions.pdfSergiuMatei7
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxAnkitaVerma776806
 

Similar to Csharp4 basics (20)

Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
C# overview part 1
C# overview part 1C# overview part 1
C# overview part 1
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)
 
Presentation 2
Presentation 2Presentation 2
Presentation 2
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
Object Oriented Programming with C++
Object Oriented Programming with C++Object Oriented Programming with C++
Object Oriented Programming with C++
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
C programming language
C programming languageC programming language
C programming language
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
Programming in C - interview questions.pdf
Programming in C - interview questions.pdfProgramming in C - interview questions.pdf
Programming in C - interview questions.pdf
 
Basic of c &c++
Basic of c &c++Basic of c &c++
Basic of c &c++
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 

Recently uploaded

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 

Csharp4 basics

  • 1. Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com
  • 2. 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
  • 3. using System; namespace Najah { public class FirstClass { static void Main() { Console.WriteLine(&quot;Hello World.&quot;); Console.ReadLine(); return; } } } Your first C# Program
  • 4. 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 false int x = 10, bool y = true; // This won't compile! Declaring Variables
  • 5. 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 use return 0; } // Compiler : Use of unassigned local variable 'd ' initialization of Variables
  • 6. 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 the previous 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 Variables reference
  • 7. 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
  • 8. using System; namespace Najah { class Program { static void Main(string[] args) { var name = “Ahmad&quot;; var age = 25; var isHuman = true; Type nameType = name.GetType(); Type ageType = age.GetType(); Type isHumanType = isHuman.GetType(); Console.WriteLine(&quot;name is type &quot; + nameType.ToString()); Console.WriteLine(&quot;age is type &quot; + ageType.ToString()); Console.WriteLine(&quot; isHuman is type &quot; + isHumanType.ToString()); } } } var Example name is type System.String age is type System.Int32 isHuman is type System.Bool
  • 9. ➤ 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
  • 10. 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 code int x = 30; Variable scope
  • 11. 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.
  • 12. 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 scope Console.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 in this scope because it would give a different meaning to 'j', which is already used in a 'parent or current' scope to denote something else.
  • 13. 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
  • 14.
  • 15. ➤ 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 in memory storing the value 20 // i and j are both of type int i = 20; j = i; Predefined data Types
  • 16. ➤ 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 class y = x; Console.WriteLine( y .Value); //30 y.Value = 50; Console.WriteLine( x .Value);//50 Predefined data Types
  • 17. ➤ Reference types : If a variable is a reference, it is possible to indicate that it does not refer to any object by setting its value to null : y = null; Predefined data Types
  • 18. Predefined Value Types integer Types:
  • 19. 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. The long 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 = 0x 12ab; 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 following characters 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).
  • 20. 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 append the character F (or f) to it: float f = 12.3F;
  • 21. 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;
  • 22. 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 to use zero for false and a non-zero value for true.
  • 23. 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 throw an error.
  • 24. Predefined Value Types Character Type cont.: As well as representing chars as character literals, you can represent them with four-digit hex Unicode values (for example ‘0041’), as integer values with a cast (for example, (char)65), or as hexadecimal values (‘0041’). You can also represent them with an escape sequence, as shown in the following table.
  • 25. Predefined reference Types object and string, : The object Type : a root type, we will study it later..! The string type: string str1 = &quot;Hello &quot;; string str2 = &quot;World&quot;; string str3 = str1 + str2; // string concatenation
  • 26. Predefined reference Types The string type cont.: using System; class StringExample { public static int Main() { string s1 = &quot;a string&quot;; string s2 = s1; Console.WriteLine(&quot;s1 is &quot; + s1); Console.WriteLine(&quot;s2 is &quot; + s2); s1 = &quot;another string&quot;; Console.WriteLine(&quot;s1 is now &quot; + s1); Console.WriteLine(&quot;s2 is now &quot; + s2); return 0; } } s1 is a string s2 is a string s1 is now another string s2 is now a string
  • 27. Predefined reference Types cont. The string type cont.: string filepath = &quot;C:DotNETClubFirst.cs&quot;; string filepath = @&quot;C:DotNETClub irst.cs&quot;; string jabberwocky = @“’Hi for All How are you?.&quot;; OUT ' Hi for All How are you?.
  • 28. The if statement if (condition) statement(s) else statement(s) //------------------------------------------------------- bool isZero; if (i == 0) { isZero = true; Console.WriteLine(&quot;i is Zero&quot;); } else { isZero = false; Console.WriteLine(&quot;i is Non-zero&quot;); }
  • 29. The if statement class MainEntryPoint { static void Main(string[] args) { Console.WriteLine(&quot;Type in a string&quot;); string input; input = Console.ReadLine(); if (input == &quot;&quot;) { Console.WriteLine(&quot;You typed in an empty string.&quot;); } else if (input.Length < 5) { Console.WriteLine(&quot;The string had less than 5 characters.&quot;); } else if (input.Length < 10) { Console.WriteLine(&quot;The string had at least 5 but less than 10 Characters.&quot;); } Console.WriteLine(&quot;The string was &quot; + input); } }
  • 30. The switch statement switch (integerA) { case 1: Console.WriteLine(&quot;integerA =1&quot;); break; case 2: Console.WriteLine(&quot;integerA =2&quot;); break; case 3: Console.WriteLine(&quot;integerA =3&quot;); break; default: Console.WriteLine(&quot;integerA is not 1,2, or 3&quot;); break; }
  • 31. The switch statement cont. switch(country) { case &quot;America&quot;: CallAmericanOnlyMethod(); goto case &quot;Britain&quot;; case &quot;France&quot;: language = &quot;French&quot;; break; case &quot;Britain&quot;: language = &quot;English&quot;; break; }
  • 32. The switch statement cont. switch(country) { case &quot;au&quot;: case &quot;uk&quot;: case &quot;us&quot;: language = &quot;English&quot;; break; case &quot;at&quot;: case &quot;de&quot;: language = &quot;German&quot;; break; }
  • 33. The switch statement cont. // assume country is of type string const string palestine= “ps&quot;; const string jordan= “ps&quot;; switch(country) { case palestine : case jordan : // This will cause a compilation error. language = “Arabic&quot;; break; }
  • 34. 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); }
  • 35. Loops – For cont. // This loop iterates through rows for (int i = 0; i < 100; i+=10) { // This loop iterates through columns for (int j = i; j < i + 10; j++) { Console.Write(&quot; &quot; + j); } Console.WriteLine(); } The preceding sample results in this output: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  • 36. 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 }
  • 37. The do . . . while loop bool condition; do { // This loop will at least execute once, even if Condition is false. MustBeCalledAtLeastOnce(); condition = CheckCondition(); } while (condition);
  • 38. 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); }
  • 39. jump statements- The goto statement goto Label1; Console.WriteLine(&quot;This won't be executed&quot;); Label1: Console.WriteLine(&quot;Continuing execution from here&quot;); In general, it certainly doesn’t conform to good object-oriented programming practice.
  • 40. jump statements- The break statement You have already met the break statement briefly — when you used it to exit from a case in a switch statement. In fact, break can also be used to exit from for, foreach, while, or do...while loops. Control will switch to the statement immediately after the end of the loop.
  • 41. jump statements- The continue statement The continue statement is similar to break, and must also be used within a for, foreach, while, or do...while loop. However, it exits only from the current iteration of the loop, meaning that execution will restart at the beginning of the next iteration of the loop, rather than outside the loop altogether.
  • 42. 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. If the method has a return type, return must return a value of this type; otherwise if the method returns void, you should use return without an expression.
  • 43. Enumerations An enumeration is a user-defined integer type. public enum TimeOfDay { Morning = 0, Afternoon = 1, Evening = 2 }
  • 44. 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(&quot;Good morning!&quot;); break; case TimeOfDay.Afternoon: Console.WriteLine(&quot;Good afternoon!&quot;); break; case TimeOfDay.Evening: Console.WriteLine(&quot;Good evening!&quot;); break; default: Console.WriteLine(&quot;Hello!&quot;); break; }}}
  • 45. 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), &quot;afternoon&quot;, true); Console.WriteLine((int)time2);
  • 46. Namespaces namespace 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... } }
  • 47. 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; } } |
  • 48. namespace aliases using 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; }}}
  • 49. multiple Main() methods using 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.cs Microsoft (R) Visual C# 2010 Compiler version 4.0.20506.1 Copyright (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 that contains 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 that contains the entry point. csc DoubleMain.cs /main:Najah.MathExample
  • 50. 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
  • 51. more on Compiling C# files The class library namespace Najah { public class MathLib { public int Add(int x, int y) { return x + y; } } } csc /t:library MathLibrary.cs
  • 52. 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
  • 53. 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(&quot;{0} plus {1} equals {2}&quot;, i, j, i + j); 10 plus 20 equals 30
  • 54. Console I/O cont. decimal i = 940.23m; decimal j = 73.7m; Console.WriteLine(&quot; {0,9:C2}+{1,9:C2} —— {2,9:C2}&quot;, 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(&quot;{0:#.00}&quot;, d);//.23
  • 55. internal Comments within the source files // This is a singleline comment /* This comment spans multiple lines. */ Console.WriteLine( /* Here's a comment! */ &quot;This will compile.&quot;); DoSomething(Width, /*Height*/ 100); string s = &quot;/* This is just a normal string .*/&quot;;
  • 57. 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=&quot;x&quot;>First number to add</param> ///<param name=&quot;y&quot;>Second number to add</param> public int Add(int x, int y) { return x + y; } } }
  • 58. Xml documentation cont. csc /t:library /doc:MathLibrary.xml MathLibrary.cs <?xml version=&quot;1.0&quot;?> <doc> <assembly> <name>MathLibrary</name> </assembly> <members> <member name=&quot;T:Najah.MathLibrary&quot;> <summary> Najah.MathLibrary class. Provides a method to add two integers. </summary> </member> <member name=&quot;M:Wrox.MathLibrary.Add(System.Int32,System.Int32)&quot;> < summary > The Add method allows us to add two integers. < /summary > < returns > Result of the addition (int) < /returns > < param name=&quot;x&quot; > First number to add < /param > < param name=&quot;y&quot; > Second number to add < /param > < /member > < /members > < /doc >
  • 59. 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 #endif int DoSomeWork(double x) { // do something #if DEBUG Console.WriteLine(&quot;x is &quot; + x); #endif }
  • 60. 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 || . A symbol 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
  • 61. The C# PreProcessor directives cont. #warning and #error #if DEBUG & & RELEASE #error &quot; You've defined DEBUG and RELEASE simultaneously !&quot; #endif #warning &quot; Don't forget to remove this line before the boss tests the code!&quot; Console.WriteLine(&quot;*I hate this job.*&quot;); #region Member Field Declarations int x; double d; Currency balance; #endregion #region and #endregion
  • 62. The C# PreProcessor directives cont. #line #line 164 &quot;Core.cs&quot; // 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 169 public class MyClass { int neverUsedField; } #pragma warning restore 169 #pragma
  • 63. 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.
  • 65. C# Programming guidelines cont. Names: ➤ Name ➤ Überfluß ➤ _Identifier ➤ 005fIdentifier
  • 66. Thanks For Attending Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com