SlideShare a Scribd company logo
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
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
➤  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 ‘\u0041’),  as integer values with a cast (for example, (char)65), or as hexadecimal values (‘\x0041’). 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:\\DotNETClub\\First.cs&quot;; string filepath = @&quot;C:\ DotNETClub \First.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}\n+{1,9:C2}\n —— \n {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 ➤  \u005fIdentifier
Thanks For Attending Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com

More Related Content

PPSX
INTRODUCTION TO C PROGRAMMING
DOCX
Unit 1 question and answer
PPTX
Python Interview questions 2020
PPTX
PPTX
C# lecture 2: Literals , Variables and Data Types in C#
PPT
Lecture 1
PPTX
Structure of c_program_to_input_output
PPTX
C++
 
INTRODUCTION TO C PROGRAMMING
Unit 1 question and answer
Python Interview questions 2020
C# lecture 2: Literals , Variables and Data Types in C#
Lecture 1
Structure of c_program_to_input_output
C++
 

What's hot (20)

PPTX
Tokens in C++
PPT
C presentation book
PPTX
datatypes and variables in c language
PPT
C material
PPT
Data type in c
PPT
Declaration of variables
ODP
Basic C Programming language
PPTX
Chapter 2 c#
PPTX
Variables and data types in C++
PPTX
Data Types and Variables In C Programming
PPTX
Data Types, Variables, and Constants in C# Programming
PPT
C language Unit 2 Slides, UPTU C language
PPTX
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
PDF
C notes.pdf
PPTX
C++ Basics
PDF
C programming notes
PPTX
Structured Languages
PDF
Pc module1
PPT
C++ Programming Course
PPT
Unit 4 Foc
Tokens in C++
C presentation book
datatypes and variables in c language
C material
Data type in c
Declaration of variables
Basic C Programming language
Chapter 2 c#
Variables and data types in C++
Data Types and Variables In C Programming
Data Types, Variables, and Constants in C# Programming
C language Unit 2 Slides, UPTU C language
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C notes.pdf
C++ Basics
C programming notes
Structured Languages
Pc module1
C++ Programming Course
Unit 4 Foc
Ad

Viewers also liked (14)

PPT
Introduction to Programming
PPT
Csharp4 delegates lambda_and_events
PDF
Secure mvc application saineshwar
PPT
Whats New In C# 3.0
PPT
Csharp4 arrays and_tuples
PDF
Free MVC project to learn for beginners.
PPTX
C# language
PPT
Logic Formulation 3
PPTX
PPTX
Introduction to .NET Core & ASP.NET Core MVC
PPTX
Introduction to C# 6.0 and 7.0
PPT
Komunikasyon
PPTX
Dynamic Programming
PPTX
Minto pyramid
Introduction to Programming
Csharp4 delegates lambda_and_events
Secure mvc application saineshwar
Whats New In C# 3.0
Csharp4 arrays and_tuples
Free MVC project to learn for beginners.
C# language
Logic Formulation 3
Introduction to .NET Core & ASP.NET Core MVC
Introduction to C# 6.0 and 7.0
Komunikasyon
Dynamic Programming
Minto pyramid
Ad

Similar to Csharp4 basics (20)

PPT
02 Primitive data types and variables
PPTX
unit 1 (1).pptx
PPTX
02. Primitive Data Types and Variables
PPTX
CSharp Presentation
PPT
Introduction of C# BY Adarsh Singh
PPTX
2 programming with c# i
PPTX
Lesson 4 Basic Programming Constructs.pptx
PPTX
Spf Chapter4 Variables
PPT
Introduction To C#
PPTX
5variables in c#
PPTX
Notes(1).pptx
PDF
434090527-C-Cheat-Sheet. pdf C# program
PDF
Lesson 1 INTRODUCTION TO C# LANGUAGE.pdf
PPTX
SPF Getting Started - Console Program
PPTX
Getting Started - Console Program and Problem Solving
PDF
CSharpCheatSheetV1.pdf
PPTX
CSharp Language Overview Part 1
PPT
Visula C# Programming Lecture 2
ODP
Ppt of c vs c#
02 Primitive data types and variables
unit 1 (1).pptx
02. Primitive Data Types and Variables
CSharp Presentation
Introduction of C# BY Adarsh Singh
2 programming with c# i
Lesson 4 Basic Programming Constructs.pptx
Spf Chapter4 Variables
Introduction To C#
5variables in c#
Notes(1).pptx
434090527-C-Cheat-Sheet. pdf C# program
Lesson 1 INTRODUCTION TO C# LANGUAGE.pdf
SPF Getting Started - Console Program
Getting Started - Console Program and Problem Solving
CSharpCheatSheetV1.pdf
CSharp Language Overview Part 1
Visula C# Programming Lecture 2
Ppt of c vs c#

More from Abed Bukhari (6)

PPT
Csharp4 generics
PPT
Csharp4 strings and_regular_expressions
PPT
Csharp4 operators and_casts
PPT
Csharp4 objects and_types
PPT
Csharp4 inheritance
PPT
Whats new in_csharp4
Csharp4 generics
Csharp4 strings and_regular_expressions
Csharp4 operators and_casts
Csharp4 objects and_types
Csharp4 inheritance
Whats new in_csharp4

Recently uploaded (20)

PPTX
Tartificialntelligence_presentation.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
TLE Review Electricity (Electricity).pptx
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Mushroom cultivation and it's methods.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
August Patch Tuesday
Tartificialntelligence_presentation.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
SOPHOS-XG Firewall Administrator PPT.pptx
cloud_computing_Infrastucture_as_cloud_p
Spectral efficient network and resource selection model in 5G networks
Per capita expenditure prediction using model stacking based on satellite ima...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
A comparative analysis of optical character recognition models for extracting...
Assigned Numbers - 2025 - Bluetooth® Document
Unlocking AI with Model Context Protocol (MCP)
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
TLE Review Electricity (Electricity).pptx
A comparative study of natural language inference in Swahili using monolingua...
Building Integrated photovoltaic BIPV_UPV.pdf
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Mushroom cultivation and it's methods.pdf
Spectroscopy.pptx food analysis technology
August Patch Tuesday

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. 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
  • 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 ‘\u0041’), as integer values with a cast (for example, (char)65), or as hexadecimal values (‘\x0041’). 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:\\DotNETClub\\First.cs&quot;; string filepath = @&quot;C:\ DotNETClub \First.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}\n+{1,9:C2}\n —— \n {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 ➤ \u005fIdentifier
  • 66. Thanks For Attending Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com