FundamentalProgramming withC#
C# Syntax• Like C/C++ and Java
Identifiers
Identifiers (Cont.)• Consist of Unicode characters• Can begin with a letter or an underscore• Cannot a keywords  • eg. int...
Capitalization Styles• Pascal case, eg. MyValue• Camel case, eg. myValueNumber• Uppercase, eg. UI
Keywords
Literals
Operators
Punctuators
StatementsThere are different kinds of statement in C#:• A code block• Declaration statements• Expression statements• Sele...
Comments
TypesEvery piece of data in C# must have a type. This is a keypart of C# being a strongly typed programminglanguage. The C...
Value TypesValue-type variables directly contain their data—that is tosay that the content of a value-type variable is its...
Value Types (Cont.)
Reference TypesReference types come in two parts—an object and the reference to thatobject. Here is a statement that creat...
Definite Assignment and NullReferencesC# requires that you assign a value to a variable before you read the valueof the va...
Common Programming TasksThe chapters that follow focus on the major features ofC#: classes, methods, fields, parameters, d...
Assigning ValuesThe C# assignment operator is the equals sign (=).Figure 4-13 shows how the assignment operator isused to ...
Making ComparisionsThe C# comparison operator (==) is used to determinewhether two variables are the same.
Making Comparisons (Cont.)
Performing SelectionsSelection statements let you select blocks of codestatements to be executed if a condition is met. C#...
Using an if StatementWith an if statement, you define a block of code statementsthat are performed only if a condition is ...
Adding else if ClausesYou can choose between code blocks by adding else if clauses toan if statement, like this:if (x == 5...
Adding an else clauseAn if statement can contain a single else clause that will beperformed if the condition in the statem...
Using a switch StatementA switch statement selects one of a set of code statements to execute bycomparing a value to a set...
Using a switch Statement(Cont.)
Jumping to Another Switch SectionYou can combine the statements in switch sections by using a gotocase statement, which ju...
Iterating Data ItemsOne of the most common programming tasks is toperform the same series of actions for eachelement in a ...
Using a for LoopA for loop repeatedly performs a block of statements while a conditionremains true. Before the first itera...
Breaking Out of a for LoopYou can terminate a for loop before the condition evaluatesto false by using the break keyword, ...
Continuing to the Next IterationNormally a for loop will perform all the statements in the codeblock before moving on to t...
Using a do…while Loop
Using a while Loop
Numeric TypesC# has a number of predefined numeric types thatcan be referred to using keywords. I tend use thekeywords, ra...
Numeric Types (Cont.)
Using Numeric LiteralsC# allows you to define numeric values literally sothat you can just use the value of the number in ...
Using Numeric OperatorsNumeric types have limited value on theirown; they need to be combined withoperators that allow you...
Using Numeric Operators(Cont.)
Arithmetic OperatorsC# includes basic arithmetic operators thatallow you to perform basic calculations.
Unary OperatorsThe C# unary operators are so-called because they work ona single numeric value.
Unary Operators (Cont.)// define a numberfloat f = 26.765f;// use the unary plus operatorfloat up = +f;// use the unary mi...
Relational OperatorsThe C# relational operators allow you to compareone numeric type to another.
Assignment OperatorsWith one exception, the assignment operators allow you toconveniently apply one of the other operators...
Assignment Operators(Cont.)The assignment operators allow shorthand when you wantto perform an operation on a variable and...
Classes and ObjectsYou create new functionality in C#programs by defining classes.Classes are the blueprints used tocreate...
Creating a Basic ClassRemember that classes are the blueprints from which objects arecreated. Imagine we had a blueprint f...
Creating a Basic Class(Cont.)This class is so simple that it doesn’t do anything yet, butwe’ll add some features as we wor...
Adding features to a ClassIt is as though we wrote “Volvo C30” on a blueprintand then just walked away. If we gave the blu...
Adding FieldsA field is a piece of information that each object created from the classwill have; this can be one of the bu...
Adding MethodsMethods let your object perform actions. That’s a prettywide definition, and the nature of your methods will...
Adding Methods (Cont.)public class VolvoC30 {    public string CarOwner;    public string PaintColor;    public int MilesP...
Adding a ConstructorA constructor is a special method that you use when creating a new object, allowing youto provide data...
Creating Objects fromClassesObjects are often referred to as instances, for example,“This object is an instance of the Vol...
Creating Objects from Classes(Cont.)
Using ObjectsOnce we have created an object, we can work with it usingthe members we defined in the class. Working with an...
Reading and Modifying FieldsTo read the value of a field, we use the dot operator (.) to combine thename we have given to ...
Using Static FieldsThe fields in all the examples in the previous sections have been instance fields,meaning that each obj...
Using Static Fields (Cont.)public int CalculateFuelForTrip(int tripDistance) {        return tripDistance / MilesPerGallon...
Calling MethodsA new object doesn’t just get a set of fields and properties; it also gets its own set ofmethods. In our Vo...
Calling Methods (Cont.)public void PrintCarDetails() {        System.Console.WriteLine("--- Car Details ---");        Syst...
Using Access ModifiersYou can restrict the use of a class by applying an access modifier to the classdefinition.
Upcoming SlideShare
Loading in...5
×

Chapter3: fundamental programming

1,489

Published on

មេរៀន C# ជំពូកទី៣

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,489
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
17
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Chapter3: fundamental programming

  1. 1. FundamentalProgramming withC#
  2. 2. C# Syntax• Like C/C++ and Java
  3. 3. Identifiers
  4. 4. Identifiers (Cont.)• Consist of Unicode characters• Can begin with a letter or an underscore• Cannot a keywords • eg. int, string, double, …
  5. 5. Capitalization Styles• Pascal case, eg. MyValue• Camel case, eg. myValueNumber• Uppercase, eg. UI
  6. 6. Keywords
  7. 7. Literals
  8. 8. Operators
  9. 9. Punctuators
  10. 10. StatementsThere are different kinds of statement in C#:• A code block• Declaration statements• Expression statements• Selection statements• Iteration statements• Control statements
  11. 11. Comments
  12. 12. TypesEvery piece of data in C# must have a type. This is a keypart of C# being a strongly typed programminglanguage. The C# compiler and runtime both use thetype of each data item to reduce some kinds ofprogramming problems.There are two kinds of types in C#: value types andreference types. The distinction between the two causesprogrammers new to object-oriented programming a lotof confusion.
  13. 13. Value TypesValue-type variables directly contain their data—that is tosay that the content of a value-type variable is its value. Thefollowing statement assigns a value of 25 to a variablecalled myInt. The type of the variable myInt is int, which is avalue type.
  14. 14. Value Types (Cont.)
  15. 15. Reference TypesReference types come in two parts—an object and the reference to thatobject. Here is a statement that creates a reference-type object:StringBuilder myObject = new StringBuilder("Adam");The StringBuilder type holds a string of characters. Figure 4-10 showsthe reference type in memory. You don’t deal with the object directly—instead, you work with it via the reference.
  16. 16. Definite Assignment and NullReferencesC# requires that you assign a value to a variable before you read the valueof the variable. The compiler checks your code to ensure that every paththrough your code assigns a value to every variable that you read. This iscalled definite assignment.The assignment of a value doesn’t need to occur when you declare thevariable; you just have to make sure that you have made an assignmentbefore you read the variable value. Here are some statements thatdemonstrate this:int myInt; // declare a variable, but dont assign to itmyInt = 20; // assign a value to the variableint sum = 100 + myInt; // we can read the value because wehave made an assignment
  17. 17. Common Programming TasksThe chapters that follow focus on the major features ofC#: classes, methods, fields, parameters, delegates, andso on. These are such important topics that it can beeasy to overlook the tasks that are most commonlyrequired of programmers. In the following sections, Idescribe how to assign values to variables, makecomparisons between values, selectively execute blocksof code, and iterate over data items.
  18. 18. Assigning ValuesThe C# assignment operator is the equals sign (=).Figure 4-13 shows how the assignment operator isused to assign a value to a variable.
  19. 19. Making ComparisionsThe C# comparison operator (==) is used to determinewhether two variables are the same.
  20. 20. Making Comparisons (Cont.)
  21. 21. Performing SelectionsSelection statements let you select blocks of codestatements to be executed if a condition is met. C#supports two selection statements—the if statement andthe switch statement.
  22. 22. Using an if StatementWith an if statement, you define a block of code statementsthat are performed only if a condition is met.
  23. 23. Adding else if ClausesYou can choose between code blocks by adding else if clauses toan if statement, like this:if (x == 50) { Console.WriteLine("First Code Block Selected");} else if (x == 60) { Console.WriteLine("Second Code Block Selected");} else if (x == 100) { Console.WriteLine("Third Code Block Selected");}
  24. 24. Adding an else clauseAn if statement can contain a single else clause that will beperformed if the condition in the statement and all of theconditions in any else if clauses evaluate to false. The else clausemust come at the end of the if statement, like this:if (x == 100) { Console.WriteLine("First Code Block Selected");} else { Console.WriteLine("Second Code Block Selected");}
  25. 25. Using a switch StatementA switch statement selects one of a set of code statements to execute bycomparing a value to a set of constants.string myName = "Adam Freeman";switch (myName) { case "Joe Smith": Console.WriteLine("Name is Joe Smith"); break; case "Adam Freeman": Console.WriteLine("Name is Adam Freeman"); break; default: Console.WriteLine("Default reached"); break;}
  26. 26. Using a switch Statement(Cont.)
  27. 27. Jumping to Another Switch SectionYou can combine the statements in switch sections by using a gotocase statement, which jumps to the specified section, as follows:switch (myName) { case "Joe Smith": Console.WriteLine("Name is Joe Smith"); break; case "Adam Freeman": Console.WriteLine("Name is Adam Freeman, Jane Jones or PeterKent"); goto case "Joe Smith"; default: Console.WriteLine("Default reached"); break;}
  28. 28. Iterating Data ItemsOne of the most common programming tasks is toperform the same series of actions for eachelement in a sequence of data items—for example,items in an array or a collection (see in nextChapter). C# supports four ways of performingiterations.
  29. 29. Using a for LoopA for loop repeatedly performs a block of statements while a conditionremains true. Before the first iteration, an initializer executes one ormore expressions. At the end of each iteration, an iterator executes oneor more statements. Another iteration will be performed if thecondition evaluates to true.
  30. 30. Breaking Out of a for LoopYou can terminate a for loop before the condition evaluatesto false by using the break keyword, like this:for (int i = 0; i < 100; i++) { Console.WriteLine("Iteration for value: {0}", i); if (i == 5) { break; }}
  31. 31. Continuing to the Next IterationNormally a for loop will perform all the statements in the codeblock before moving on to the next iteration. By using thecontinue keyword, you can move to the next iteration withoutperforming any statements that follow. Here is an example:for (int i = 0; i < 5; i++) { Console.WriteLine("Iteration for value: {0}", i); if (i == 2 || i == 3) { continue; } Console.WriteLine("Reached end of iteration for value: {0}",i);}
  32. 32. Using a do…while Loop
  33. 33. Using a while Loop
  34. 34. Numeric TypesC# has a number of predefined numeric types thatcan be referred to using keywords. I tend use thekeywords, rather than the type names, but differentprogrammers have varying styles, and it is useful toknow how the keywords and the types relate toeach other. There is no advantage in using onestyle over the other; the C# compiler converts thekeywords into the correct type automatically, whichmeans that you can mix keywords and types freely,even in the same code.
  35. 35. Numeric Types (Cont.)
  36. 36. Using Numeric LiteralsC# allows you to define numeric values literally sothat you can just use the value of the number in astatement, like this:
  37. 37. Using Numeric OperatorsNumeric types have limited value on theirown; they need to be combined withoperators that allow you to performcalculations and otherwise manipulate thevalues they represent. In the followingsections, I describe the five kinds of numericoperator that C# supports.
  38. 38. Using Numeric Operators(Cont.)
  39. 39. Arithmetic OperatorsC# includes basic arithmetic operators thatallow you to perform basic calculations.
  40. 40. Unary OperatorsThe C# unary operators are so-called because they work ona single numeric value.
  41. 41. Unary Operators (Cont.)// define a numberfloat f = 26.765f;// use the unary plus operatorfloat up = +f;// use the unary minus operatorfloat um = -f;// print out the resultsConsole.WriteLine("Unary plus result: {0}",up);Console.WriteLine("Unary minus result: {0}",um);
  42. 42. Relational OperatorsThe C# relational operators allow you to compareone numeric type to another.
  43. 43. Assignment OperatorsWith one exception, the assignment operators allow you toconveniently apply one of the other operators and assignthe result in a single step.
  44. 44. Assignment Operators(Cont.)The assignment operators allow shorthand when you wantto perform an operation on a variable and assign the resultto the same variable. So, these statements:int x = 10;x = x + 2;can be written as follows:int x = 10;x += 2;
  45. 45. Classes and ObjectsYou create new functionality in C#programs by defining classes.Classes are the blueprints used tocreate the objects that you use torepresent items in your program.
  46. 46. Creating a Basic ClassRemember that classes are the blueprints from which objects arecreated. Imagine we had a blueprint for a car; for the sake of anexample, let’s say the blueprint is for a 2010 Volvo C30. Theblueprint specifies every detail of the car, but it isn’t a car itself. Itjust describes how the car should be constructed. We have to gothrough the process of constructing a car from the blueprint toend up with something that we can get into and drive away, andthat something will be a Volvo C30, because that’s what we usedas the blueprint.public class VolvoC30 { // class body}
  47. 47. Creating a Basic Class(Cont.)This class is so simple that it doesn’t do anything yet, butwe’ll add some features as we work through.
  48. 48. Adding features to a ClassIt is as though we wrote “Volvo C30” on a blueprintand then just walked away. If we gave the blueprint tosomeone else, they’d have only the name to go on. Wehave not provided any information about whatfeatures we require. We add features to a class byadding class members. There are a range of differentcategories of class members, some of which aredescribed in the following sections. All of the differentmember types are described in depth in the chaptersthat follow.
  49. 49. Adding FieldsA field is a piece of information that each object created from the classwill have; this can be one of the built-in value types that C# supports(such as a number or a Boolean value), or it can be another object (areference type). If a field refers to another object, then that object canbe one of those included with the .NET Framework (such as a string), orit can be a type we have created, like the VolvoC30 class.public class VolvoC30 { public string CarOwner; public string PaintColor; public int MilesPerGallon= 30;}
  50. 50. Adding MethodsMethods let your object perform actions. That’s a prettywide definition, and the nature of your methods willdepend on the nature of your class. If we remain with thecar metaphor, then we could have methods to start theengine, open the window, plot a navigation route, and soon. If our class represented a person, we might havemethods that change marital status, employment status,and relationships, with objects representing other people.
  51. 51. Adding Methods (Cont.)public class VolvoC30 { public string CarOwner; public string PaintColor; public int MilesPerGallon = 30; public int CalculateFuelForTrip(int tripDistance) { return tripDistance / MilesPerGallon; } public void PrintCarDetails() { System.Console.WriteLine("--- Car Details ---"); System.Console.WriteLine("Car Owner: {0}", CarOwner); System.Console.WriteLine("Car Color: {0}", PaintColor); System.Console.WriteLine("Gas Mileage: {0} mpg",MilesPerGallon); }}
  52. 52. Adding a ConstructorA constructor is a special method that you use when creating a new object, allowing youto provide data via parameters that will set the initial state of the object.
  53. 53. Creating Objects fromClassesObjects are often referred to as instances, for example,“This object is an instance of the VolvoC30 class.” This isoften shortened so that it is commonly said that “This is aninstance of VolvoC30.” To create an object from a class, weuse the new operator, sometimes referred to as theconstruction or instantiation operator. We tell the newoperator which class to work with, and it creates a newobject of the type representing by the class.
  54. 54. Creating Objects from Classes(Cont.)
  55. 55. Using ObjectsOnce we have created an object, we can work with it usingthe members we defined in the class. Working with anobject typically means doing one of two things: changingthe value of a field to change the state of an object or usingone of the objects methods to perform an action. Methodscan modify the value of fields as well, so sometimes you’llbe performing a calculation and modifying the state of anobject in one go.
  56. 56. Reading and Modifying FieldsTo read the value of a field, we use the dot operator (.) to combine thename we have given to the object instance and the name of the fieldwe want to access.// create a new object of the VolvoC30 typeVolvoC30 myCar = new VolvoC30("Adam Freeman", "Black");// create a second VolvoC30 objectVolvoC30 joesCar = new VolvoC30("Joe Smith", "Silver");// read the value of the myCar.CarOwner fieldstring owner = myCar.CarOwner;Console.WriteLine("Field value: {0}", owner);
  57. 57. Using Static FieldsThe fields in all the examples in the previous sections have been instance fields,meaning that each object has its own field. This is why we have to use the objectreference with the dot operator to access the field. We have to tell the .NET runtimewhich object’s field we want to work with.public class VolvoC30 { public string CarOwner; public string PaintColor; public int MilesPerGallon = 30; public static int EngineCapacity = 2000; public VolvoC30(string newOwner, string paintColor) { CarOwner = newOwner; PaintColor = paintColor; }
  58. 58. Using Static Fields (Cont.)public int CalculateFuelForTrip(int tripDistance) { return tripDistance / MilesPerGallon; } public void PrintCarDetails() { System.Console.WriteLine("--- Car Details ---"); System.Console.WriteLine("Car Owner: {0}", CarOwner); System.Console.WriteLine("Car Color: {0}", PaintColor); System.Console.WriteLine("Gas Mileage: {0} mpg", MilesPerGallon); System.Console.WriteLine("Engine Capacity: {0} cc", EngineCapacity); }}
  59. 59. Calling MethodsA new object doesn’t just get a set of fields and properties; it also gets its own set ofmethods. In our VolvoC30 class, we defined two methods, called PrintCarDetails andCalculateFuelForTrip.public class VolvoC30 { public string CarOwner; public string PaintColor; public int MilesPerGallon = 30; public VolvoC30(string newOwner, string paintColor) { CarOwner = newOwner; PaintColor = paintColor; }
  60. 60. Calling Methods (Cont.)public void PrintCarDetails() { System.Console.WriteLine("--- Car Details ---"); System.Console.WriteLine("Car Owner: {0}", CarOwner); System.Console.WriteLine("Car Color: {0}", PaintColor); System.Console.WriteLine("Gas Mileage: {0} mpg",MilesPerGallon); }}
  61. 61. Using Access ModifiersYou can restrict the use of a class by applying an access modifier to the classdefinition.
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×