SlideShare une entreprise Scribd logo
1  sur  23
The C# Language ,[object Object]
Variables and Data Types
Array, ArrayList, Enumerations
Operator & Math Functions
Type Conversions
The DateTime and TimeSpan Types
Conditional Logic
Loops
Methods & Method Overloading
Parameters (Optional & Named)
Delegates,[object Object]
Commenting// A single-line C# comment. /* A multiple-line C# comment. */ ,[object Object]
Blocks{ // Code statements go here. } ,[object Object],interrorCode; string myName;
Variables and Data Types
Variables and Data Types
Escaped Characters • quot; (double quote) •  (new line) •  (horizontal tab) •  (backward slash) // A C# variable holding the // c:yAppyFiles path. path = "c:MyAppMyFiles"; Alternatively, you can turn off C# escaping by preceding a string with an @ symbol, as shown here: path = @"c:yAppyFiles";
Arrays Arrays allow you to store a series of values that have the same data type. // Create an array with four strings (from index 0 to index 3). // You need to initialize the array with the new keyword in order to use it. string[] stringArray = new string[4]; // Create a 2x4 grid array (with a total of eight integers). int[,] intArray = new int[2, 4]; // Create an array with four strings, one for each number from 1 to 4. string[] stringArray = {"1", "2", "3", "4"}; // Create a 4x2 array (a grid with four rows and two columns). int[,] intArray = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
ArrayList ArrayListdynamicList = new ArrayList(); // Add several strings to the list. The ArrayList is not strongly typed, so you can add any data type dynamicList.Add("one"); dynamicList.Add(2); dynamicList.Add(true); // Retrieve the first string. Notice that the object must be converted to a // string, because there's no way for .NET to be certain what it is. string item = Convert.ToString(dynamicList[0]);
Enumeration An enumeration is a group of related constants, each of which is given a descriptive name. Each value in an enumeration corresponds to a preset integer. enumUserType { Admin, Guest, Invalid }
Operators & Math functions +, -, *, / ,% are basic operators To use the math operations, you invoke the methods of the System.Math class.  myValue = Math.Round(42.889, 2); // myValue = 42.89 myValue = Math.Abs(-10); // myValue = 10.0 myValue = Math.Log(24.212); // myValue = 3.18.. (and so on) myValue = Math.PI; // myValue = 3.14.. (and so on)
Type Conversions Converting information from one data type to another Conversions are of two types: widening and narrowing. Widening conversions always succeed.  For example, you can always convert a 32-bit integer into a 64-bit integer. intmySmallValue; long myLargeValue; mySmallValue= Int32.MaxValue; myLargeValue = mySmallValue; Or  mySmallValue = (int)myLargeValue; intmyInt=1000; short count; count=(short)myInt;
Type Conversions Converting information from one data type to another String myString; intmyInteger=100; myString=myInteger.ToString(); String countString=“10”; int count=Convert.ToInt32(countString); or int count=Int32.Parse(countString);
String Functions Length() :                                       myString.Length() ToUpper(), ToLower()		myString.ToUpper()		   Trim()					myString.Trim() Substring()				myString.SubString(0,2) StartsWith(), EndsWith()		myString.StartsWith(“pre”) PadLeft(), PadRight()		myString.PadLeft(5,”*”) Insert()                                           myString.Insert(1,”pre) Remove()				myString.Remove(0,2) Split()					myString.Split(“,”) Join()					myString1.Join(myString2) Replace()				myString.Replace(“a”,”b”)

Contenu connexe

Tendances

Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structureSaad Gabr
 
C Prog - Pointers
C Prog - PointersC Prog - Pointers
C Prog - Pointersvinay arora
 
Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Ali Aminian
 
Ch6 pointers (latest)
Ch6 pointers (latest)Ch6 pointers (latest)
Ch6 pointers (latest)Hattori Sidek
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskellJongsoo Lee
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APIMario Fusco
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++Ilio Catallo
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQIntro C# Book
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2Warui Maina
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text ProcessingIntro C# Book
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)stasimus
 

Tendances (20)

Lec2
Lec2Lec2
Lec2
 
Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structure
 
C Prog - Pointers
C Prog - PointersC Prog - Pointers
C Prog - Pointers
 
Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2
 
Monad Fact #4
Monad Fact #4Monad Fact #4
Monad Fact #4
 
Ch6 pointers (latest)
Ch6 pointers (latest)Ch6 pointers (latest)
Ch6 pointers (latest)
 
130717666736980000
130717666736980000130717666736980000
130717666736980000
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
Arrays
ArraysArrays
Arrays
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
Arrays
ArraysArrays
Arrays
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 

Similaire à C# Language Basics Guide

C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0Yaser Zhian
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionSvetlin Nakov
 
How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012Connor McDonald
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handlingsanya6900
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
QTP Presentation2
QTP Presentation2QTP Presentation2
QTP Presentation2vucevic
 

Similaire à C# Language Basics Guide (20)

C# basics
C# basicsC# basics
C# basics
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
 
How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
CP 04.pptx
CP 04.pptxCP 04.pptx
CP 04.pptx
 
Unit 3
Unit 3 Unit 3
Unit 3
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 
Java Generics
Java GenericsJava Generics
Java Generics
 
QTP Presentation2
QTP Presentation2QTP Presentation2
QTP Presentation2
 
Bw14
Bw14Bw14
Bw14
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 

Plus de application developer (20)

Chapter 26
Chapter 26Chapter 26
Chapter 26
 
Chapter 25
Chapter 25Chapter 25
Chapter 25
 
Chapter 23
Chapter 23Chapter 23
Chapter 23
 
Assignment
AssignmentAssignment
Assignment
 
Next step job board (Assignment)
Next step job board (Assignment)Next step job board (Assignment)
Next step job board (Assignment)
 
Chapter 19
Chapter 19Chapter 19
Chapter 19
 
Chapter 18
Chapter 18Chapter 18
Chapter 18
 
Chapter 17
Chapter 17Chapter 17
Chapter 17
 
Chapter 16
Chapter 16Chapter 16
Chapter 16
 
Week 3 assignment
Week 3 assignmentWeek 3 assignment
Week 3 assignment
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
Chapter 13
Chapter 13Chapter 13
Chapter 13
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
 
Chapter 11
Chapter 11Chapter 11
Chapter 11
 
Chapter 10
Chapter 10Chapter 10
Chapter 10
 
C # test paper
C # test paperC # test paper
C # test paper
 
Chapter 9
Chapter 9Chapter 9
Chapter 9
 
Chapter 8 part2
Chapter 8   part2Chapter 8   part2
Chapter 8 part2
 
Chapter 8 part1
Chapter 8   part1Chapter 8   part1
Chapter 8 part1
 

Dernier

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 

Dernier (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

C# Language Basics Guide

  • 1.
  • 4. Operator & Math Functions
  • 6. The DateTime and TimeSpan Types
  • 9. Methods & Method Overloading
  • 11.
  • 12.
  • 13.
  • 16. Escaped Characters • quot; (double quote) • (new line) • (horizontal tab) • (backward slash) // A C# variable holding the // c:yAppyFiles path. path = "c:MyAppMyFiles"; Alternatively, you can turn off C# escaping by preceding a string with an @ symbol, as shown here: path = @"c:yAppyFiles";
  • 17. Arrays Arrays allow you to store a series of values that have the same data type. // Create an array with four strings (from index 0 to index 3). // You need to initialize the array with the new keyword in order to use it. string[] stringArray = new string[4]; // Create a 2x4 grid array (with a total of eight integers). int[,] intArray = new int[2, 4]; // Create an array with four strings, one for each number from 1 to 4. string[] stringArray = {"1", "2", "3", "4"}; // Create a 4x2 array (a grid with four rows and two columns). int[,] intArray = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
  • 18. ArrayList ArrayListdynamicList = new ArrayList(); // Add several strings to the list. The ArrayList is not strongly typed, so you can add any data type dynamicList.Add("one"); dynamicList.Add(2); dynamicList.Add(true); // Retrieve the first string. Notice that the object must be converted to a // string, because there's no way for .NET to be certain what it is. string item = Convert.ToString(dynamicList[0]);
  • 19. Enumeration An enumeration is a group of related constants, each of which is given a descriptive name. Each value in an enumeration corresponds to a preset integer. enumUserType { Admin, Guest, Invalid }
  • 20. Operators & Math functions +, -, *, / ,% are basic operators To use the math operations, you invoke the methods of the System.Math class. myValue = Math.Round(42.889, 2); // myValue = 42.89 myValue = Math.Abs(-10); // myValue = 10.0 myValue = Math.Log(24.212); // myValue = 3.18.. (and so on) myValue = Math.PI; // myValue = 3.14.. (and so on)
  • 21. Type Conversions Converting information from one data type to another Conversions are of two types: widening and narrowing. Widening conversions always succeed. For example, you can always convert a 32-bit integer into a 64-bit integer. intmySmallValue; long myLargeValue; mySmallValue= Int32.MaxValue; myLargeValue = mySmallValue; Or mySmallValue = (int)myLargeValue; intmyInt=1000; short count; count=(short)myInt;
  • 22. Type Conversions Converting information from one data type to another String myString; intmyInteger=100; myString=myInteger.ToString(); String countString=“10”; int count=Convert.ToInt32(countString); or int count=Int32.Parse(countString);
  • 23. String Functions Length() : myString.Length() ToUpper(), ToLower() myString.ToUpper() Trim() myString.Trim() Substring() myString.SubString(0,2) StartsWith(), EndsWith() myString.StartsWith(“pre”) PadLeft(), PadRight() myString.PadLeft(5,”*”) Insert() myString.Insert(1,”pre) Remove() myString.Remove(0,2) Split() myString.Split(“,”) Join() myString1.Join(myString2) Replace() myString.Replace(“a”,”b”)
  • 24. DateTime and TimeSpan Types DateTime and Timespane data types have built-in methods and properties Methods & Properties of DateTime : Now Today Year, Date, Month ,Hour, Minute, Second, and Millisecond Add() and Subtract() AddYears(), AddMonths(), AddDays(), AddHours, AddMinutes() DaysIn Month() Methods and Properties of TimeSpan: Days, Hours, Minutes, Seconds, Milliseconds TotalDays, TotalHours, TotalMinutes, TotalSeconds, TotalMilliseconds Add() and Subtract() FromDays(), FromHours(), From Minutes(), FromSeconds()
  • 25. DateTime and TimeSpan Types DateTimemyDate = DateTime.Now; myDate = myDate.AddDays(100); DateTime myDate2 = DateTime.Now.AddHours(3000); TimeSpan difference; difference = myDate2.Subtract(myDate1); double numberOfMinutes; numberOfMinutes = difference.TotalMinutes; // Adding a TimeSpan to a DateTime creates a new DateTime. DateTime myDate1 = DateTime.Now; TimeSpan interval = TimeSpan.FromHours(3000); DateTime myDate2 = myDate1 + interval; // Subtracting one DateTime object from another produces a TimeSpan. TimeSpan difference; difference = myDate2 - myDate1;
  • 26. Conditional Logic All conditional logic starts with a condition: a simple expression that can be evaluated to true or false. Your code can then make a decision to execute different logic depending on the outcome of the condition. To build a condition, you can use any combination of literal values or variables along with logical operators == Equal to != Not Equal to < Less than > Greater than <= Less than or equal to >= Greater than or equal to && Logical and || Logical or
  • 27. Conditional Logic The switch Statement switch (myNumber) { case 1: // Do something. break; case 2: // Do something. break; default: // Do something. break; } The if Statement if (myNumber > 10) { // Do something. } else if (myString == "hello") { // Do something. } else { // Do something
  • 28. Loops Loops allow you to repeat a segment of code multiple times. C# has three basic types of loops • You can loop a set number of times with a for loop. • You can loop through all the items in a collection of data using a foreachloop. • You can loop while a certain condition holds true with a while or do…while loop. THE FOR LOOP string[] stringArray = {"one", "two", "three"}; for (int i = 0; i < stringArray.Length; i++) { System.Diagnostics.Debug.Write(stringArray[i] ); } THE FOREACH LOOP foreach (string element in stringArray) { System.Diagnostics.Debug.Write(element ); }
  • 29. Loops THE WHILE LOOP inti = 0; while (i < 10) { i += 1; // This code executes ten times. } You can also place the condition at the end of the loop using the do…while syntax. In this case, the condition is tested at the end of each pass through the loop: THE DO WHILE LOOP inti = 0; do { i += 1; // This code executes ten times. } while (i < 10);
  • 30. Methods A method also known as function is a named grouping of one or more lines of code. Each method will perform a distinct, logical task. By breaking your code down into methods, you not only simplify your life, but you also make it easier to organize your code into classes // This method doesn't return any information. void MyMethodNoReturnedData() { // Code goes here. } // This method returns an integer. intMyMethodReturnedData() { // As an example, return the number 10. return 10; }
  • 31. Parameter Optional Parameter private string GetUserName(int ID, booluseShortForm = false) { // Code here. } name = GetUserName(401, true); name = GetUserName(401); Use Named parameter for multiple optional parameters: private decimal GetSalesTotalForRegion(intregionID, decimal minSale = 0, decimal maxSale = Decimal.MaxValue, boolincludeTax = false) { // Code here. } total = GetSalesTotalForRegion(523, maxSale: 5000);
  • 32. Delegates Delegates allow you to create a variable that “points” to a method. private string TranslateEnglishToFrench(); { } private delegate string translateLanguage(string inputString); translateLanguage translate; translate=TranslateEnglishToFrench; string frenchString; frenchString=translate(“Hello”); You can make delegate point to any other function also if it has same signature
  • 33. Delegates private string TranslateEnglishToSpanish(); { } translate=TranslateEnglishToSpanish; string spanishString; spanishString=translate(“Hello”); private string TranslateEnglishToGerman(); { } translate=TranslateEnglishToGerman; string germanString; germanString=translate(“Hello”);
  • 34. Summary It’s impossible to do justice to an entire language in a single chapter. However, if you’ve programmed before, you’ll find that this chapter provides all the information you need to get started with the C# language. As you work through the full ASP.NET examples in the following chapters, you can refer to this chapter to clear up any language issues. In the next chapter, you’ll learn about more important language concepts and the object-oriented nature of .NET.