C# programming in easy steps pdf download






















Essentials of Computer Architecture, 2nd Edition. Handbook of Big Data Technologies. Please enter your comment! Please enter your name here. You have entered an incorrect email address! Follow Us! Latest Books. Articulate Storyline Essentials 18 June Beginning SharePoint Development 18 June Beginning SharePoint 18 June Popular Categories.

NET version to run the code. Please note that the ebook PDF version for sale in our online shop has now been updated for Visual Studio Products search. C Programming in easy steps quantity.

SKU: Title summary Description Table of Contents Resources Updates Learn C language basics, including variables, arrays, logic, looping, methods, and classes, and how to install the Visual Studio Community Edition.

Then move on to Object Oriented Programming — all in easy steps! Declaring Variables Variables hold values. C has many different types of values that it can store and process—integers, floating-point numbers, and strings of characters, to name three. When you declare a variable, you must specify the type of data it will hold. For example, the following statement declares that the variable named age holds int integer values. As always, the statement must be terminated with a semicolon. The variable type int is the name of one of the primitive C types, integer, which is a whole number.

You must explicitly declare all variables before you use them. The following statement assigns age the value After this assignment, you can use the age variable in your code to refer to the value it holds. The next statement writes the value of the age variable, 42, to the console:.

Working with Primitive Data Types C has a number of built-in types called primitive data types. The following table lists the most com- monly used primitive data types in C and the range of values that you can store in each. Unassigned Local Variables When you declare a variable, it contains a random value until you assign a value to it.

C does not allow you to use an unassigned variable. You must assign a value to a variable before you can use it, otherwise your program will not compile. This requirement is called the definite assignment rule. WriteLine statement attempts to display the value of an uninitialized variable:. A so- lution can contain one or more projects. Project files have the. If you open a project rather than a solution, Visual Studio automatically creates a new solution file for it.

This situation can be confusing if you are not aware of this feature, as it can result in you accidentally generating multiple solutions for the same project. If you attempt to open a solution for a Windows Store app by using Visual Studio on Windows 7, the project will fail to load. You might see some warnings in Visual Studio. You can safely ignore them. You will correct them in the next exercise. Click each data type in the list. Confirm that the code for the double and bool types is not yet implemented.

This control displays the list of data types in the left part of the form, and it looks like this some of the properties have been removed from this text :. When the application is running, if a user clicks an item in the list, the SelectionChanged event occurs this is a little bit like the Clicked event that occurs when the user clicks a button, which you saw in Chapter 1. You can see that in this case, the ListBox invokes the typeSelectionChanged method. This method is defined in the MainWindow.

Click the arrow to the left of the MainWindow. A menu opens in the top-right corner of the Code and Text Editor window. By default, the search is not case sensitive. If you want to perform a case-sensitive search, click the down arrow next to the text to search for, click the drop-down ar- row to the right of the text box in the shortcut menu to display additional options, and then select the Match Case check box.

If you have time, you can experiment with the other options as well. The class members drop-down list box displays all the methods in the class, together with the variables and other items that the class contains. You will learn more about these items in later chapters. In the drop-down list, click the typeSelectionChanged method, and the cursor will move directly to the typeSelectionChanged method in the class.

At present, all you need to understand is that when the user clicks an item in the ListBox control, the value of the item is passed to this method, which then uses this value to determine happens next. For example, if the user clicks the float value, then this method calls another method named showFloatValue.

The body of this method contains three statements. The first statement declares a variable named variable of type float. The second statement assigns variable the value 0. The F is a type suffix specifying that 0.

If you forget the F, the value 0. The third statement displays the value of this variable in the Value text box on the form. This statement requires your attention. If you remember from Chapter 1, the way in which you dis- play an item in a text box is to set its Text property you did this by using XAML in Chapter 1. You can also perform this task programmatically, which is what is going on here. Notice that you access the property of an object by using the same dot notation that you saw for running a method.

Remember Console. WriteLine from Chapter 1? Also, the data that you put in the Text property must be a string and not a number. If you try to assign a number to the Text property, your program will not compile. Fortunately, the. Every data type in the. The purpose of ToString is to convert an object to its string representation. The showFloatValue method uses the ToString method of the float variable floatVar object to generate a string version of the value of this variable.

This string can then be safely assigned to the Text property of the Value text box. When you create your own data types and classes, you can define your own implementa- tion of the ToString method to specify how your class should be represented as a string.

Type the following two statements at the start of the showIntValue method, on a new line after the opening brace, as shown in bold type in the following code:. The first statement creates a variable called intVar that can hold an int value. The second statement assigns the value 42 to this variable. Select the int type in the Choose a Data Type list. Confirm that the value 42 is displayed in the Sample Value text box.

This code is similar to the showIntValue method, except that it creates a variable called doubleVar that holds double values, and it is assigned the value 0. Again, this code is similar to the previous examples, except that boolVar can only hold a Bool- ean value, true or false. In the Choose a Data Type list, select the int, double, and bool types. In each case, verify that the correct value is displayed in the Sample Value text box. In the following example, the variable moneyPaidToConsultant ends up holding the prod- uct of the daily rate and 20 the number of days the consultant was employed :.

Operators and Types Not all operators are applicable to all data types. For example, you can use all the arithmetic operators on values of type char, int, long, float, double, or decimal.

So the following statement is not allowed, because the string type does not support the minus operator subtracting one string from another is meaningless :. You need to be careful because this can have unexpected results.

NET Framework provides a method called Int Parse that you can use to convert a string value to an integer if you need to perform arithmetic computations on values held as strings. For example, the value of the expression 5. In C , literal numbers with decimal points are always double, not float, to maintain as much accuracy as possible.

In this case, the type of both operands is int, so the type of the result is also int. C always rounds toward zero in circumstances like this. The situation gets a little more complicated if you mix the types of the operands. The C compiler detects the mismatch and generates code that converts the int into a double before performing the operation.

The result of the operation is therefore a double 2. However, although this works, it is considered poor practice to mix types in this way. However, C relaxes this rule. The remainder operator is valid with all numeric types, and the result is not necessarily an integer. For example, the result of the expression 7. Numeric Types and Infinite Values There are one or two other features of numbers in C that you should be aware of.

However, the double and float types actually have a special value that can represent infin- ity, and the value of the expression 5. The one exception to this rule is the value of the expression 0. Usually, if you divide zero by anything, the result is zero, but if you divide anything by zero the result is infinity.

The expression 0. NaN and Infinity propagate through expressions. The one exception to this rule is the case when you multiply Infinity by 0. Type 54 in the Left Operand text box. The text in the Expression text box changes to 54 — 13, but the value 0 appears in the Result box; this is clearly wrong. Test the other combinations of numbers and operators; you will find that they all currently yield the value 0.

As you may have guessed, none of the calculations is currently implemented by the MathsOperators application. In the next exercise, you will correct this. Display the MainWindow. Double-click the file Main- Window.

The Document Outline window appears, showing the names and types of the controls on the form. The Document Outline window provides a simple way to locate and select controls on a complex form. The controls are arranged in a hierarchy, starting with the Page Windows 8 or Window Windows 7 that constitutes the form.

As mentioned in the previous chapter, a Windows Store app page or a WPF form contains a Grid control, and the other controls are placed in this Grid.

If you expand the Grid node in the Document Outline window, the other. If you expand the inner Grid, you can see each of the controls on the form. If you click any of these controls, the corresponding element is highlighted in the Design View window. Similarly, if you select a control in the Design View window, the corresponding control is selected in the Document Outline window pin the Document Outline window in place by deselect- ing the Auto Hide button in the top-right corner of the Document Outline window to see this in action.

On the form, click the two TextBox controls in which the user types numbers. In the Document Outline window, verify that they are named lhsOperand and rhsOperand. When the form runs, the Text property of each of these controls holds the values that the user enters. Toward the bottom of the form, verify that the TextBlock control used to display the expres- sion being evaluated is named expression and that the TextBlock control used to display the result of the calculation is named result.

In the Code and Text Editor window, locate the addValues method. Parse lhsOperand. Parse rhsOperand. Text; result. The first statement in this method declares an int variable called lhs and initializes it with the integer corresponding to the value typed by the user in the lhsOperand text box. Remember that the Text property of a TextBox control contains a string, but lhs is an int, so you must convert this string to an integer before you can assign it to lhs.

The int data type provides the int. Parse method, which does precisely this. The second statement declares an int variable called rhs and initializes it to the value in the rhsOperand text box after converting it to an int.

A comment stating that you need to add rhs to lhs and store the result in outcome follows. This is the missing bit of code that you need to implement, which you will do in the next step. Text property. This causes the string to appear in the Expression text box on the form. The final statement displays the result of the calculation by assigning it to the Text property of the Result text box.

Remember that the Text property is a string, and the result of the calcula- tion is an int, so you must convert the int to a string before assigning it to the Text property.

Recall that this is what the ToString method of the int type does. Underneath the comment in the middle of the addValues method, add the statement shown below in bold:.

Examine the subtractValues method. You should see that it follows a similar pattern, and you need to add the statement to calculate the result of subtracting rhs from lhs and storing it in outcome. Add the statement shown below in bold to this method:. Examine the mutiplyValues, divideValues, and remainderValues methods.

Again, they all have the crucial statement that performs the specified calculation missing. Add the appropriate statements to these methods shown below in bold. Click the — Subtraction button and then click Calculate. Verify that the result is now Verify that the result is now 4. When you divide one integer by another integer, the answer you get back is an inte- ger, as explained earlier.

Verify that the result is now 2. This is because the calculation rounds down to an integer at each stage. Return to Visual Studio and stop debugging or click Quit if you are using Windows 7. This expression is potentially ambiguous: do you perform the addition first or the multiplication? The order of the operations matters because it changes the result:. The term square brackets refers to [ ]. Using Associativity to Evaluate Expressions Operator precedence is only half the story.

What happens when an expression contains different op- erators that have the same precedence? This is where associativity becomes important. Associativity is the direction left or right in which the operands of an operator are evaluated. At first glance, this expression is potentially ambiguous. Do you perform the division first or the multiplication? The precedence of both operators is the same they are both multiplicative , but the order in which the operators in the expression are applied is important because you can get two dif- ferent results:.

In this case, the associativity of the operators determines how the expression is evaluated. All operators return a value based on their operands. It takes two operands: the operand on its right side is evalu- ated and then stored in the operand on its left side. The value of the assignment operator is the value that was assigned to the left operand. For example, in the following assignment statement, the value returned by the assignment operator is 10, which is also the value assigned to the variable myInt:.

Well, be- cause the assignment operator returns a value, you can use this same value with another occurrence of the assignment statement, like this:. The value assigned to the variable myInt2 is the value that was assigned to myInt. The assignment statement assigns the same value to both variables. This technique is useful if you want to initialize several variables to the same value.

It makes it very clear to anyone reading your code that all the variables must have the same value:. From this discussion, you can probably deduce that the assignment operator associates from right to left. The rightmost assignment occurs first, and the value assigned propagates through the variables from right to left. If any of the variables previously had a value, it is overwritten by the value being assigned. You should treat this construct with caution, however.

One frequent mistake that new C program- mers make is to try to combine this use of the assignment operator with variable declarations. For example, you might expect the following code to create and initialize three variables with the same value 10 :. This is legal C code because it compiles. What it does is declare the variables myInt, myInt2, and myInt3, and initialize myInt3 with the value However, it does not initialize myInt or myInt2.

If you try to use myInt or myInt2 in an expression such as this:. Use of unassigned local variable 'myInt' Use of unassigned local variable 'myInt2'. To increment the variable count by 1, you can write the following statement:. They share the same precedence and are both left-associative. Placing the operator symbol before the variable is called the prefix form of the operator, and using the operator symbol after the variable is called the postfix form.

Here are examples:. Here is an example:. The way to remember which operand does what is to look at the order of the elements the op- erand and the operator in a prefix or postfix expression. It was also mentioned that you should assign a value to a variable before you attempt to use it. You can declare and initialize a variable in the same statement, like this:. Or you can even do it like this, assuming that myOtherInt is an initialized integer variable:.

Now, remember that the value you assign to a variable must be of the same type as the variable. For example, you can assign an int value only to an int variable. The C compiler can quickly work out the type of an expression used to initialize a variable and indicate if it does not match the type of the variable. You can also ask the C compiler to infer the type of a variable from an expression and use this type when declaring the variable by using the var keyword in place of the type, like this:.

The variables myVariable and myOtherVariable are referred to as implicitly typed variables. The var keyword causes the compiler to deduce the type of the variables from the types of the expres- sions used to initialize them. In these examples, myVariable is an int, and myOtherVariable is a string. However, it is important for you to understand that this is a convenience for declaring variables only, and that after a variable has been declared you can assign only values of the inferred type to it—you cannot assign float, double, or string values to myVariable at a later point in your program, for example.

You should also understand that you can use the var keyword only when you supply an expression to initialize a variable. The following declaration is illegal and causes a compilation error:. I empha- size here and now that you should forget everything you ever learned when programming with Visual Basic about Variant variables.

Although the keywords look similar, var and Variant mean totally different things. When you declare a variable in C using the var key- word, the type of values that you assign to the variable cannot change from that used to initialize the variable.

After all, it sounds like an excuse for extreme laziness on the part of programmers and can make it more difficult to understand what a program is doing or track down bugs and it can even easily introduce new bugs into your code.

However, trust me that var has a very valid place in C , as you will see when you work through many of the following chapters. However, for the time being, we will stick to using explicitly typed variables except for when implicit typing becomes a necessity. Summary In this chapter, you have seen how to create and use variables, and you have learned about some of the common data types available for variables in C. You have learned about identifiers. In addition, you have used a number of operators to build expressions, and you have learned how the precedence and associativity of operators determine how expressions are evaluated.

For example: int outcome;. Declare a variable and give it an initial value Write the name of the data type, followed by the name of the vari- able, followed by the assignment operator and the initial value.

Finish with a semicolon. Change the value of a variable Write the name of the variable on the left, followed by the assign- ment operator, followed by the expression calculating the new value, followed by a semicolon. Generate a string representation of the value Call the ToString method of the variable.

ToString ;. Convert a string to an int Call the System. Parse method. Parse stringVar ;. Override the precedence of an operator Use parentheses in the expression to force the order of evaluation. Assign the same value to several variables Use an assignment statement that lists all the variables. This information is useful when you need to trace the execu- tion of your methods if they do not work quite as you expect. Creating Methods A method is a named sequence of statements.

A method has a name and a body. The method name should be a meaningful identifier that indicates the overall purpose of the method calculateIncomeTax, for example. The method body con- tains the actual statements to be run when the method is called. Additionally, methods can be given some data for processing and can return information, which is usually the result of the processing.

Methods are a fundamental and powerful mechanism. This can be any type, such as int or string. Method names follow the same identifier rules as variable names.

For now, you should follow the camelCase convention for method names— for example, displayCustomer. You must write all your methods inside a class; otherwise, your code will not compile. You cannot use the var keyword. You must always specify either a return type or void. Returning Data from a Method If you want a method to return information that is, its return type is not void , you must include a return statement at the end of the processing in the method body.

A return statement consists of the keyword return followed by an expression that specifies the returned value, and a semicolon. The type of the expression must be the same as the type specified by the method declaration. For example, if a method returns an int, the return statement must return an int; otherwise, your program will not compile.

Here is an example of a method with a return statement:. The return statement is usually positioned at the end of the method because it causes the method to finish, and control returns to the statement that called the method, as described later in this chap- ter.

Any statements that occur after the return statement are not executed although the compiler warns you about this problem if you place statements after the return statement.

You write the keyword return immediately followed by a semicolon. Although this practice is common, it is not always considered good style. In the following exercise, you will examine another version of the MathsOperators project from Chapter 2. This version has been improved by the careful use of some small methods. Dividing code in this way helps to make it easier to understand and more maintainable. Visual Studio builds and runs the application. It should look the same as the application from Chapter 2.

Refamiliarize yourself with the application and how it works, and then return to Visual Studio. Display the code for MainWindow. The addValues method contains two statements. The first statement displays the calcula- tion being performed in the expression text box on the form. Remember that adding two int values together creates another int value, so the return type of the addValues method is int.

If you look at the methods subtractValues, multiplyValues, divideValues, and remainderValues, you will see that they follow a similar pattern.

This method contains one statement that displays a string representation of the answer parameter in the result text box. It does not return a value, so the type of this method is void. If a method helps to avoid repetition and makes your program easier to understand, the method is useful regardless of how small it is. There is also no maximum length for a method, but usually you want to keep your method code small enough to get the job done. If your method is more than one screen in length, consider breaking it into smaller methods for readability.

Calling Methods Methods exist to be called! You call a method by name to ask it to perform its task. If the method requires information as specified by its parameters , you must supply the information requested. If the method returns information as specified by its return type , you should arrange to capture this information somehow.

Remember, C is a case-sensitive language. If specified, the variable identified by result contains the value returned by the method. If the method is void that is, it does not return a value , you must. You must supply an argu- ment for each parameter, and the value of each argument must be compatible with the type of its corresponding parameter.

The addValues method has two int parameters, so you must call it with two comma-separated int arguments, such as this:. You can also replace the literal values 39 and 3 with the names of int variables.

The values in those variables are then passed to the method as its arguments, like this:. If you try to call addValues in some other way, you will probably not succeed for the reasons described in the following examples:.

The addValues method returns an int value. This int value can be used wherever an int value can be used. Consider these examples:. The following exercise continues with the Methods application. This time, you will examine some method calls. Return to the Methods project. Locate the calculateClick method, and look at the first two statements of this method after the try statement and opening brace. Text ;. These two statements declare two int variables, called leftHandSide and rightHandSide.

Notice the way in which the variables are initialized. In both cases, the Parse method of the System. Int32 class is called. System is a namespace, and Int32 is the name of the class in this namespace. You have seen this method before—it takes a single string parameter and converts it to an int value.

These two lines of code take whatever the user has typed into the lhsOperand and rhsOperand text box controls on the form and converts them to int values. Look at the fourth statement in the calculateClick method after the if statement and another opening brace :. This statement calls the addValues method, passing the values of the leftHandSide and right- HandSide variables as its arguments.

The value returned by the addValues method is stored in the calculatedValue variable. This statement calls the showResult method, passing the value in the calculatedValue variable as its argument. The showResult method does not return a value. Notice that the ToString method call uses parentheses even though there are no arguments. In the preceding example, the expression answer. ToString calls the method named ToString belonging to the object called answer. Applying Scope You create variables to hold values.

You can create variables at various points in your applica- tions. For example, the calculateClick method in the Methods project creates an int variable called calculatedValue and assigns it an initial value of zero, like this:. This variable comes into existence at the point where it is defined, and subsequent statements in the calculateClick method can then use this variable. This is an important point: a variable can be used only after it has been created. When the method has finished, this variable disappears and cannot be used elsewhere.

When a variable can be accessed at a particular location in a program, the variable is said to be in scope at that location. The calculatedValue variable has method scope; it can be accessed throughout the calculateClick method but not outside of that method.

You can also define variables with different scope; for example, you can define a variable outside of a method but within a class, and this variable can be accessed by any method within that class. Such a variable is said to have class scope. To put it another way, the scope of a variable is simply the region of the program in which that variable is usable. Scope applies to methods as well as variables.

The scope of an identifier of a variable or method is linked to the location of the declaration that introduces the identifier in the program, as you learn next. Defining Local Scope The opening and closing braces that form the body of a method define the scope of the method. Any variables you declare inside the body of a method are scoped to that method; they disappear when the method ends and can be accessed only by code running in that method.

These variables are called local variables because they are local to the method in which they are declared; they are not in scope in any other method. Consider this example:. This code fails to compile because anotherMethod is trying to use the variable myVar, which is not in scope. The variable myVar is available only to statements in firstMethod that occur after the line of code that declares myVar.

Defining Class Scope The opening and closing braces that form the body of a class define the scope of that class. Any variables you declare inside the body of a class but not inside a method are scoped to that class. The proper C term for a variable defined by a class is field. As mentioned earlier, in contrast with local variables, you can use fields to share information between methods. The variable myField is defined in the class but outside the methods firstMethod and another Method.

Therefore, myField has class scope and is available for use by all methods in the class. There is one other point to notice about this example. In a method, you must declare a variable before you can use it. Fields are a little different. A method can use a field before the statement that defines the field—the compiler sorts out the details for you. Often an overloaded identifier is a bug that gets trapped as a compile-time error.

For example, if you declare two local variables with the same name in the same method, the compiler reports an error. Similarly, if you declare two fields with the same name in the same class, or two iden- tical methods in the same class, you also get a compile-time error. This fact might seem hardly worth mentioning, given that everything so far has turned out to be a compile-time error. However, there is a way that you can overload an identifier for a method, and that way is both useful and important.

Consider the WriteLine method of the Console class. You have already used this method for writing a string to the screen. Each version of the WriteLine method takes a different set of parameters; one version takes no parameters and simply outputs a blank line, another version takes a bool parameter and outputs a string representation of its value True or False , yet another implementation takes a decimal parameter and outputs it as a string, and so on.

At compile time, the compiler looks at the types of the arguments you are passing in and then arranges for your application to call the version of the method that has a matching set of parameters.

WriteLine "The answer is " ; Console. Overloading is primarily useful when you need to perform the same operation on different data types or varying groups of information. You can overload a method when the different implementations have different sets of parameters—that is, when they have the same name but a different number of parameters, or when the types of the parameters differ. When you call a method, you supply a comma-separated list of arguments, and the number and type of the arguments are used by the compiler to select one of the overloaded methods.

The compiler is clever, but not that clever. You will start by developing the logic for the applica- tion and then use the Generate Method Stub Wizard to help you write the methods that are used by this logic. In Solution Explorer, double-click the file Program. This program is simply a test harness for you to try out your code.



0コメント

  • 1000 / 1000