1 / 74

Introduction to C#

Explore the fundamentals of C# programming language through practical examples. Understand key concepts and syntax differences from Python. Start your coding journey today!

Download Presentation

Introduction to C#

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to C# 01204111 Computer and Programming

  2. Agenda • Why two languages? • Differences betweenPython andC# • C# overview • Event-driven programming

  3. Why Two Languages? • There exist many languages which are quite different from each other • Python is easy for beginners, but its flexibility makes it different from other languages you will likely use • The two languages were carefully chosen so that they have distinct syntax • So you will see and learn various programming styles

  4. Our First C# Program What does this program do? using System;class Program{public static void Main(string[] args)  {    Random r = newRandom();int answer = 1 + (r.Next() % 100);int g; do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());if(g > answer)        Console.WriteLine("Too large");elseif(g < answer)        Console.WriteLine("Too small");    } while(g != answer);     Console.WriteLine("That's correct");  }}

  5. Dissect The Program using System;class Program{public static void Main(string[] args)  {    Random r = newRandom();int answer = 1 + (r.Next() % 100);int g; do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());if(g > answer)        Console.WriteLine("Too large");elseif(g < answer)        Console.WriteLine("Too small");    } while(g != answer);     Console.WriteLine("That's correct");  }} The main program is contained in a function (method) called Main

  6. Dissect The Program using System;class Program{public static void Main(string[] args)  {    Random r = newRandom();int answer = 1 + (r.Next() % 100);int g; do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());if(g > answer)        Console.WriteLine("Too large");elseif(g < answer)        Console.WriteLine("Too small");    } while(g != answer);     Console.WriteLine("That's correct");  }} A pair of braces{ } are used to specify a block of code

  7. Dissect TheMethod Main public static void Main(string[] args)  {    Random r = newRandom();int answer = 1 + (r.Next() % 100);int g; do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());if(g > answer)        Console.WriteLine("Too large");elseif(g < answer)        Console.WriteLine("Too small");    } while(g != answer);     Console.WriteLine("That's correct");  } Randomly pick a number between1 - 100

  8. Dissect The MethodMain public static void Main(string[] args)  {    Random r = newRandom();int answer = 1 + (r.Next() % 100);int g; do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());if(g > answer)        Console.WriteLine("Too large");elseif(g < answer)        Console.WriteLine("Too small");    } while(g != answer);     Console.WriteLine("That's correct");  } Repeat as long as g != answer

  9. Dissect The MethodMain public static void Main(string[] args)  {    Random r = newRandom();int answer = 1 + (r.Next() % 100);int g; do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());if(g > answer)        Console.WriteLine("Too large");elseif(g < answer)        Console.WriteLine("Too small");    } while(g != answer);     Console.WriteLine("That's correct");  } Print a string, then read an integer and store it in the variable g

  10. Dissect The MethodMain public static void Main(string[] args)  {    Random r = newRandom();int answer = 1 + (r.Next() % 100);int g; do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());if(g > answer)        Console.WriteLine("Too large");elseif(g < answer)        Console.WriteLine("Too small");    } while(g != answer);     Console.WriteLine("That's correct");  } Compare gandanswer, then display the hint

  11. Dissect The MethodMain public static void Main(string[] args)  {    Random r = newRandom();int answer = 1 + (r.Next() % 100);int g; do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());if(g > answer)        Console.WriteLine("Too large");elseif(g < answer)        Console.WriteLine("Too small");    } while(g != answer);     Console.WriteLine("That's correct");  } Tell the user that the answer is correct

  12. Dissect The Program: Outer Block using System;class Program{public static void Main(string[] args)  {    Random r = newRandom();int answer = 1 + (r.Next() % 100);int g; do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());if(g > answer)        Console.WriteLine("Too large");elseif(g < answer)        Console.WriteLine("Too small");    } while(g != answer);     Console.WriteLine("That's correct");  }} Indicate that this program will use functions from standard library

  13. Dissect The Program using System;class Program{public static void Main(string[] args)  {    Random r = newRandom();int answer = 1 + (r.Next() % 100);int g; do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());if(g > answer)        Console.WriteLine("Too large");elseif(g < answer)        Console.WriteLine("Too small");    } while(g != answer);     Console.WriteLine("That's correct");  }} Every method must reside in a class

  14. Coding in Different Languages Hello,May I have a fried rice, and water please? Bonjour, Puis-je avoir un riz frit, et de l'eau s'il vous plaît? Solving the same task using a different language usually has on the same flow of thought and steps. The only differences are syntax and wording.

  15. C# Program Structure using System;namespace Sample { class Program { staticvoid Main() { Console.WriteLine("Hello, world"); } } } C# uses braces{ } to specify scopes of things Program on the left contains namespace Sample class Program method Main

  16. C# Program Structure using System;namespace Sample { class Program { staticvoid Main() { Console.WriteLine("Hello, world"); } } } C# statements are contained in a bigger structure Statements are inside a method Methods are inside a class Classes may or may not be inside a namespace

  17. The Universe of C# Programs Namespace System Namespace Sample (Our own namespace) Class X Class Console WriteLine Class Float Write ReadLine Class Program Class Integer Class Random Parse Main Next ToString … Class Y

  18. using System • The statementusing System;at the beginning of the program indicates that our program will use the System namespace as our own namespace Namespace System using System;namespace Sample { class Program { …… } } Namespace Sample (Our own namespace) Class Console WriteLine Class Float Write ReadLine Class Program Class Integer Class Random Parse Main Next ToString

  19. The Main Program: Method Main using System;namespace Sample { class Program { staticvoid Main() { } } } The program always starts at the method Main We will write our main program here.

  20. Just Ignore Them (For Now) • What are classes? • What is this"static void" thing? We will not answer these questions at the moment. For the time being, just use them as shown. You will know when the time comes…

  21. Example: Distance Calculation • A still object starts moving in a straight line with the acceleration of a m/s2 for t seconds. • How far is it from its starting point?

  22. DevelopingC# Programs • We will use a tool calledIntegrated Development Environment, orIDE • Allows code editing, testing, and debugging • Similar to WingIDE • We will first start with text-only programs • Also known as console applications

  23. Start Writing Program • The IDE we will be using is call SharpDevelop. • Microsoft Visual Studio Express can also be used.

  24. Create aSolution • A program is called asolution • Choose New Solution • ChooseConsole Application • Entersolution name • Once done, stub code will be created

  25. IDE Window • Code editor is located at the center of the window • Other parts show properties and structure of the program

  26. First Program using System;namespace mecha1{  class Program  {public static void Main(string[] args)    {double a, t, s;Console.Write("Enter a: ");      a = double.Parse(Console.ReadLine());Console.Write("Enter t: ");      t = double.Parse(Console.ReadLine());      s = a*t*t/2.0;Console.WriteLine("Distance = {0}", s);    }  }} Identify similarities and differences, compared to a Python program

  27. First Program using System;namespace mecha1{  class Program  {public static void Main(string[] args)    {double a, t, s;Console.Write("Enter a: ");      a = double.Parse(Console.ReadLine());Console.Write("Enter t: ");      t = double.Parse(Console.ReadLine());      s = a*t*t/2.0;Console.WriteLine("Distance = {0}", s);    }  }} Every statement ends with a; (semi-colon)

  28. First Program using System;namespace mecha1{  class Program  {public static void Main(string[] args)    {double a, t, s;Console.Write("Enter a: ");      a = double.Parse(Console.ReadLine());Console.Write("Enter t: ");      t = double.Parse(Console.ReadLine());      s = a*t*t/2.0;Console.WriteLine("Distance = {0}", s);    }  }} Variables must be declared with proper data types before used. Here, double is a data type for storing a real number.

  29. First Program using System;namespace mecha1{  class Program  {public static void Main(string[] args)    {double a, t, s;Console.Write("Enter a: ");      a = double.Parse(Console.ReadLine());Console.Write("Enter t: ");      t = double.Parse(Console.ReadLine());      s = a*t*t/2.0;Console.WriteLine("Distance = {0}", s);    }  }} Calculate the result and store it ins

  30. First Program using System;namespace mecha1{  class Program  {public static void Main(string[] args)    {double a, t, s;Console.Write("Enter a: ");      a = double.Parse(Console.ReadLine());Console.Write("Enter t: ");      t = double.Parse(Console.ReadLine());      s = a*t*t/2.0;Console.WriteLine("Distance = {0}", s);    }  }} Output Statements

  31. First Program using System;namespace mecha1{  class Program  {public static void Main(string[] args)    {double a, t, s;Console.Write("Enter a: ");      a = double.Parse(Console.ReadLine());Console.Write("Enter t: ");      t = double.Parse(Console.ReadLine());      s = a*t*t/2.0;Console.WriteLine("Distance = {0}", s);    }  }} Input Statement reads user input as a string

  32. First Program using System;namespace mecha1{  class Program  {public static void Main(string[] args)    {double a, t, s;Console.Write("Enter a: ");      a = double.Parse(Console.ReadLine());Console.Write("Enter t: ");      t = double.Parse(Console.ReadLine());      s = a*t*t/2.0;Console.WriteLine("Distance = {0}", s);    }  }} Convert string into real number(double)

  33. Difference: Use { } To Indicate Blocks Python C# def main(): n = int(input()) i = 1 while i <= n: if i % 3 == 0: print(i) // // Other parts are omitted // staticvoid Main() { int n = int.Parse(Console.ReadLine()); int i = 1; while(i <= n) { if(i % 3 == 0) { Console.WriteLine(i); } } } Python uses indentation C# uses { }

  34. Difference: Use{ } To Indicate Blocks C# C# // // Other parts are omitted // staticvoid Main() { int n = int.Parse(Console.ReadLine()); int i = 1; while(i <= n) { if(i % 3 == 0) { Console.WriteLine(i); } } } // // Other parts are omitted // staticvoid Main() { int n = int.Parse(Console.ReadLine()); int i = 1; while(i <= n) { if(i % 3 == 0) { Console.WriteLine(i); } } } Indentations have no effect on program logic. They are used for improving readability.

  35. Difference: Use{ } To Indicate Blocks C# C# // // Other parts are omitted // staticvoid Main() { int n = int.Parse(Console.ReadLine()); int i = 1; while(i <= n) if(i % 3 == 0) Console.WriteLine(i); } // // Other parts are omitted // staticvoid Main() { int n = int.Parse(Console.ReadLine()); int i = 1; while(i <= n) { if(i % 3 == 0) { Console.WriteLine(i); } } } For control statements such aswhile orif, omitting { } means the following block contains only one statement.

  36. Difference: Variable Declaration Python C# n = int(input()) total = 0 i = 0 while i < n: x = int(input()) total += x i += 1 print(total) // // Other parts are omitted // staticvoid Main() { int n = int.Parse(Console.ReadLine()); int total = 0; int i = 0; int x; while(i < n) { x = int.Parse(Console.ReadLine()); total += x; i += 1; } }

  37. Declaring Variables • Syntax: <Data type><Variable name>; <Data type> <Var name>,<Var name>, …; • Ex: • Initial values can be given right awayEx: Single var Multiple vars. double area; intradius, counter; boolisOkay; int k = 200; bool done = false;

  38. Basic Data Types inC#

  39. Computing Summation • Write a program that takes a list of positive integers from user until -1 is entered, then displays the sum of all the numbers in the list

  40. Summation: Python total = 0 num = 0 while num != -1: num = int(input()) if num != -1: total += num print(total)

  41. Summation: C# • Summation program written inC# static void Main() { int total = 0; int num = 0; while(num != -1) { num = int.Parse(Console.ReadLine()); if(num != -1) total += num; } Console.WriteLine(total); } total = 0 num = 0 while num != -1: num = int(input()) if num != -1: total += num print(total)

  42. C# andPython: Difference Summary C# Python • Use { } to indicate blocks • Variables • Must always be declared with data type specified • One variable can store one data type • Usually run faster • Use indentation forblocks • Variables • Can be used instantly • Each variable can store any data type, which can be changed during the program execution • Usually run slower

  43. Cost and Benefit • We lose many flexibilities in C#, but more errors can be found much earlier

  44. Erroneous Python Program x = int(input("Enter price: ")) if x <= 10: print("You have to pay",x,"baht.") else: print("You have to pay",y*0.95,"baht.") Do you spot the error? Enter price: 7 You have to pay 7 baht. We will know only when the erroneous line gets executed Enter price: 20 Traceback (most recent call last): File "<string>", line 5, in <fragment> builtins.NameError: name 'y' is not defined

  45. Erroneous C# Program public static void Main(string[] args)    {double x;Console.Write("Enter price: ");      x = double.Parse(Console.ReadLine());if(x <= 10)Console.WriteLine("You have to pay {0} baht.", x);elseConsole.WriteLine("You have to pay {0} baht.", y*0.95);            } Do you spot the error? This C# program will not compile. The compiler will report The name 'y' does not exist in the current context.

  46. Erroneous Python Program x = input("Enter price: ") if x <= 10: print("You have to pay",x,"baht.") else: print("You have to pay",x*0.95,"baht.") Do you spot the error? There is a problem because we try to compare an integer with a string Traceback (most recent call last): File "<string>", line 2, in <fragment> builtins.TypeError: unorderable types: str() <= int() We will know only when the erroneous line gets executed

  47. Erroneous C# Program public static void Main(string[] args)    {String x;Console.Write("Enter price: ");      x = Console.ReadLine();if(x <= 10)Console.WriteLine("You have to pay {0} baht.", x);elseConsole.WriteLine("You have to pay {0} baht.", x*0.95);            } Do you spot the error? This C# program won't compile. Two errors will be reported 1. Operator '<=' cannot be applied to operands of type 'string' and 'int'. 2. Operator '*' cannot be applied to operands of type 'string' and 'double'

  48. Choosing a Language Strict Unintentional errors caught before the program starts Longer programs cause more difficulties More limitations Generous Easy and faster to write program, with more flexibility Errors might be found after the program started Can be a problem with large programs

  49. Justification of This Course • This course begins with Python, which is easy for beginners • The second half uses C#, which has more restrictions, so we write more organized programs • This is to allow students to understand the programming concept, without being tied to a specific language

  50. Your Choices • There are many other programming languages • Most importantly, pick the right tool for the right job

More Related