اخى الكريم لك كل الشكر على هذا الموضوع الذى من الواضح انك قمت بجهد كبير فية بالفعل ولكن للاسف
انا خبرتى بالبرمجة قليلة جدل و بالتوفيق
اخى الكريم لك كل الشكر على هذا الموضوع الذى من الواضح انك قمت بجهد كبير فية بالفعل ولكن للاسف
انا خبرتى بالبرمجة قليلة جدل و بالتوفيق
Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.
The do-while Loop
The next loop is the do-while. Unlike the for and the while loops, in which the condition is
tested at the top of the loop, the do-while loop checks its condition at the bottom of the loop.
This means that a do-while loop will always execute at least once. The general form of the dowhile
loop is
do {
statements;
} while(condition);
Although the braces are not necessary when only one statement is present, they are often used
to improve readability of the do-while construct, thus preventing confusion with the while.
The do-while loop executes as long as the conditional expression is true.
The following program loops until the user enters the letter q:
// Demonstrate the do-while loop.
using System;
class DWDemo {
static void Main() {
char ch;
do {
Console.Write("Press a key followed by ENTER: ");
ch = (char) Console.Read(); // read a keypress
} while(ch != 'q');
}
}
---------- Post added at 07:01 PM ---------- Previous post was at 06:59 PM ----------
Using a do-while loop, we can further improve the guessing game program from earlier in
this chapter. This time, the program loops until you guess the letter.
// Guess the letter game, 4th version.
using System;
class Guess4 {
static void Main() {
char ch, answer = 'K';
do {
Console.WriteLine("I'm thinking of a letter between A and Z.");
Console.Write("Can you guess it: ");
// Read a letter, but skip cr/lf.
---------- Post added at 07:08 PM ---------- Previous post was at 07:01 PM ----------
do {
ch = (char) Console.Read();
} while(ch == '\n' | ch == '\r');
if(ch == answer) Console.WriteLine("** Right **");
else {
Console.Write("...Sorry, you're ");
if(ch < answer) Console.WriteLine("too low");
else Console.WriteLine("too high");
Console.WriteLine("Try again!\n");
}
} while(answer != ch);
}
}
Here is a sample run:
I'm thinking of a letter between A and Z.
Can you guess it: A
...Sorry, you're too low
Try again!
I'm thinking of a letter between A and Z.
Can you guess it: Z
...Sorry, you're too high
Try again!
I'm thinking of a letter between A and Z.
Can you guess it: K
** Right **
---------- Post added at 07:09 PM ---------- Previous post was at 07:08 PM ----------
Notice one other thing of interest in this program. The do-while loop shown here obtains
the next character, skipping over any carriage-return and linefeed characters that might be in
the input stream:
// read a letter, but skip cr/lf
do {
ch = (char) Console.Read(); // get a char
} while(ch == '\n' | ch == '\r');
Here is why this loop is needed. As explained earlier, console input is line-buffered—you have
to press ENTER before characters are sent. Pressing ENTER causes a carriage-return and a linefeed
character to be generated. These characters are left pending in the input buffer. This loop
discards those characters by continuing to read input until neither is present.
---------- Post added at 07:09 PM ---------- Previous post was at 07:09 PM ----------
Improve the C# Help System
This program expands on the C# help system that was begun in the previous Try This section.
This version adds the syntax for the for, while, and do-while loops. It also checks the user’s
menu selection, looping until a valid response is entered.
Step by Step
1. Copy Help.cs to a new file called Help2.cs.
2. Change the portion of the program that displays the choices so that it uses the loop
shown here:
do {
Console.WriteLine("Help on:");
Console.WriteLine(" 1. if");
Console.WriteLine(" 2. switch");
Console.WriteLine(" 3. for");
Console.WriteLine(" 4. while");
Console.WriteLine(" 5. do-while\n");
Console.Write("Choose one: ");
do {
choice = (char) Console.Read();
} while(choice == '\n' | choice == '\r');
} while( choice < '1' | choice > '5');
Notice that a nested do-while loop is used to discard any spurious carriage-return or linefeed
characters that may be present in the input stream. After making this change, the program
will loop, displaying the menu until the user enters a response that is between 1 and 5.
---------- Post added at 07:10 PM ---------- Previous post was at 07:09 PM ----------
3. Expand the switch statement to include the for, while, and do-while loops, as shown here:
switch(choice) {
case '1':
Console.WriteLine("The if:\n");
Console.WriteLine("if(condition) statement;");
Console.WriteLine("else statement;");
break;
case '2':
Console.WriteLine("The switch:\n");
Console.WriteLine("switch(expression) {");
Console.WriteLine(" case constant:");
Console.WriteLine(" statement sequence");
Console.WriteLine(" break;");
Console.WriteLine(" // ...");
Console.WriteLine("}");
break;
case '3':
Console.WriteLine("The for:\n");
Console.Write("for(init; condition; iteration)");
---------- Post added at 07:10 PM ---------- Previous post was at 07:10 PM ----------
Console.WriteLine(" statement;");
break;
case '4':
Console.WriteLine("The while:\n");
Console.WriteLine("while(condition) statement;");
break;
case '5':
Console.WriteLine("The do-while:\n");
Console.WriteLine("do {");
Console.WriteLine(" statement;");
Console.WriteLine("} while (condition);");
break;
}
Notice that no default is present in this version of the switch. Since the menu loop ensures
that a valid response will be entered, it is no longer necessary to include a default sequence
to handle an invalid choice.
---------- Post added at 07:11 PM ---------- Previous post was at 07:10 PM ----------
4. Here is the entire Help2.cs program listing:
/*
An improved Help system that uses a
do-while to process a menu selection.
*/
using System;
class Help2 {
static void Main() {
char choice;
do {
Console.WriteLine("Help on:");
Console.WriteLine(" 1. if");
Console.WriteLine(" 2. switch");
Console.WriteLine(" 3. for");
Console.WriteLine(" 4. while");
Console.WriteLine(" 5. do-while\n");
Console.Write("Choose one: ");
do {
choice = (char) Console.Read();
} while(choice == '\n' | choice == '\r');
} while( choice < '1' | choice > '5');
Console.WriteLine("\n");
switch(choice) {
case '1':
Console.WriteLine("The if:\n"); (continued)
---------- Post added at 07:11 PM ---------- Previous post was at 07:11 PM ----------
Console.WriteLine("if(condition) statement;");
Console.WriteLine("else statement;");
break;
case '2':
Console.WriteLine("The switch:\n");
Console.WriteLine("switch(expression) {");
Console.WriteLine(" case constant:");
Console.WriteLine(" statement sequence");
Console.WriteLine(" break;");
Console.WriteLine(" // ...");
Console.WriteLine("}");
break;
case '3':
Console.WriteLine("The for:\n");
Console.Write("for(init; condition; iteration)");
Console.WriteLine(" statement;");
break;
case '4':
Console.WriteLine("The while:\n");
Console.WriteLine("while(condition) statement;");
break;
case '5':
Console.WriteLine("The do-while:\n");
Console.WriteLine("do {");
Console.WriteLine(" statement;");
Console.WriteLine("} while (condition);");
break;
}
}
}
---------- Post added at 07:12 PM ---------- Previous post was at 07:11 PM ----------
Use break to Exit a Loop
It is possible to force an immediate exit from a loop, bypassing any code remaining in the
body of the loop and the loop’s conditional test, by using the break statement. When a break
statement is encountered inside a loop, the loop is terminated and program control resumes at
the next statement following the loop. Here is a simple example:
// Using break to exit a loop.
using System;
class BreakDemo {
static void Main() {
int num;
---------- Post added at 07:12 PM ---------- Previous post was at 07:12 PM ----------
num = 100;
// Loop while i squared is less than num.
for(int i=0; i < num; i++) {
// Terminate loop if i*i >= 100.
if(i*i >= num) break;
Console.Write(i + " ");
}
Console.WriteLine("Loop complete.");
}
}
This program generates the following output:
0 1 2 3 4 5 6 7 8 9 Loop complete.
---------- Post added at 07:13 PM ---------- Previous post was at 07:12 PM ----------
As you can see, although the for loop is designed to run from 0 to num (which, in this case, is
100), the break statement causes it to terminate early, when i squared is greater than or equal
to num.
The break statement can be used with any of C#’s loops, including intentionally infinite
loops. For example, the following program simply reads input until the user presses q:
// Read input until a q is received.
using System;
class Break2 {
static void Main() {
char ch;
for( ; ; ) {
ch = (char) Console.Read();
if(ch == 'q') break;
}
Console.WriteLine("You pressed q!");
}
}
When used inside a set of nested loops, the break statement will break out of only the
innermost loop. For example:
// Using break with nested loops.
using System;
class Break3 {
static void Main() {
---------- Post added at 07:13 PM ---------- Previous post was at 07:13 PM ----------
for(int i=0; i<3; i++) {
Console.WriteLine("Outer loop count: " + i);
Console.Write(" Inner loop count: ");
int t = 0;
while(t < 100) {
if(t == 10) break;
Console.Write(t + " ");
t++;
}
Console.WriteLine();
}
Console.WriteLine("Loops complete.");
}
}
This program generates the following output:
Outer loop count: 0
Inner loop count: 0 1 2 3 4 5 6 7 8 9
Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.
Outer loop count: 1
Inner loop count: 0 1 2 3 4 5 6 7 8 9
Outer loop count: 2
Inner loop count: 0 1 2 3 4 5 6 7 8 9
Loops complete.
As you can see, the break statement in the inner loop causes only the termination of that loop.
The outer loop is unaffected.
Here are two other points to remember about break. First, more than one break statement
may appear in a loop, but be careful. Too many break statements have the tendency to
destructure your code. Second, the break that exits a switch statement affects only that switch
statement and not any enclosing loops.
Q: I know that in Java, the break and continue statements can be used with a label. Does
C# support the same feature?
A: No. The designers of C# did not give break or continue that capability. Instead, break and
continue work the same in C# as they do in C and C++. One reason that C# did not follow
Java’s lead on this issue is that Java does not support the goto statement, but C# does. Thus,
Java needs to give break and continue extra power to make up for the lack of the goto.
---------- Post added at 07:15 PM ---------- Previous post was at 07:14 PM ----------
It is possible to force an early iteration of a loop, bypassing the loop’s normal control structure.
This is accomplished using continue. The continue statement forces the next iteration
of the loop to take place, skipping any code in between. Thus, continue is essentially the
complement of break. For example, the following program uses continue to help print the
even numbers between 0 and 100:
// Use continue.
using System;
class ContDemo {
static void Main() {
int i;
// Print even numbers between 0 and 100.
for(i = 0; i<=100; i++) {
// Iterate if i is odd.
if((i%2) != 0) continue;
Console.WriteLine(i);
}
}
}
---------- Post added at 07:15 PM ---------- Previous post was at 07:15 PM ----------
Only even numbers are printed, because an odd one will cause the loop to iterate early, bypassing
the call to WriteLine( ).
In while and do-while loops, a continue statement will cause control to go directly to the
conditional expression. In the case of the for, the iteration expression of the loop is evaluated
and then the conditional expression is executed.
Good uses of continue are rare. One reason is that C# provides a rich set of loop statements
that fit most applications. However, for those special circumstances in which early iteration is
needed, the continue statement provides a structured way to accomplish it.
The goto
The goto is C#’s unconditional jump statement. When encountered, program flow jumps to the
location specified by the goto. The statement fell out of favor with programmers many years ago
because it encouraged the creation of “spaghetti code,” a tangled mess of unconditional jumps
that resulted in hard-to-follow code. However, the goto is still occasionally—and sometimes
effectively—used. This book will not make a judgment regarding its validity as a form of program
control. It should be stated, however, that there are no programming situations that require the use
of the goto statement—it is not an item necessary for making the language complete. Rather, it is
a convenience, which, if used wisely, can be of benefit in certain programming situations. As such,
the goto is not used in this book outside of this section. The chief concern most programmers have
---------- Post added at 07:16 PM ---------- Previous post was at 07:15 PM ----------
about the goto is its tendency to clutter a program and render it nearly unreadable. However, there
are times when the use of the goto can clarify program flow rather than confuse it.
The goto requires a label for operation. A label is a valid C# identifier followed by a colon.
Furthermore, the label must be in the same method as the goto that uses it. For example, a loop
from 1 to 100 could be written using a goto and a label, as shown here:
x = 1;
loop1:
x++;
if(x < 100) goto loop1;
One good use for the goto is to exit from a deeply nested routine. Here is a simple example:
// Demonstrate the goto.
using System;
class Use_goto {
static void Main() {
int i=0, j=0, k=0;
for(i=0; i < 10; i++) {
for(j=0; j < 10; j++ ) {
for(k=0; k < 10; k++) {
Console.WriteLine("i, j, k: " + i + " " + j + " " + k);
if(k == 3) goto stop;
}
}
}
stop:
Console.WriteLine("Stopped! i, j, k: " + i + ", " + j + ", " + k);
}
}
The output from the program is shown here.
i, j, k: 0 0 0
i, j, k: 0 0 1
i, j, k: 0 0 2
i, j, k: 0 0 3
Stopped! i, j, k: 0, 0, 3
Eliminating the goto would force the use of three if and break statements. In this case, the
goto simplifies the code. While this is a contrived example used for illustration, you can
imagine real-world situations in which a goto might be beneficial.
The goto does have one important restriction: You cannot jump into a block. Of course,
you can jump out of a block, as the preceding example shows.
---------- Post added at 07:16 PM ---------- Previous post was at 07:16 PM ----------
In addition to working with “normal” labels, the goto can be used to jump to a case or
default label within a switch. For example, this is a valid switch statement:
switch(x) {
case 1: // ...
goto default;
case 2: // ...
goto case 1;
default: // ...
break;
}
The goto default jumps to the default label. The goto case 1 jumps to case 1. Because of the
restriction stated above, you cannot jump into the middle of a switch from code outside the
switch because a switch defines a block. Therefore, these types of goto statements must be
executed from within the switch.
Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.
ان الكتب في اللغة سي هي ستكون جيدة بخصوص هذه البرمجة
لكن اعتقد ان البمرجة لازم لها من التطبيق لكي يفهم جيدا
Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.
Finish the C# Help System
Here you will put the finishing touches on the C# help system. This version adds the syntax for
break, continue, and goto. It also allows the user to request the syntax for more than one statement.
It does this by adding an outer loop that runs until the user enters a q as a menu selection.
Step by Step
1. Copy Help2.cs to a new file called Help3.cs.
2. Surround all of the program code with an infinite for loop. Break out of this loop, using
break, when a q is entered. Since this loop surrounds all of the program code, breaking out
of this loop causes the program to terminate.
3. Change the menu loop, as shown here:
do {
Console.WriteLine("Help on:");
Console.WriteLine(" 1. if");
Console.WriteLine(" 2. switch");
Console.WriteLine(" 3. for");
Console.WriteLine(" 4. while");
Console.WriteLine(" 5. do-while");
Console.WriteLine(" 6. break");
Console.WriteLine(" 7. continue");
Console.WriteLine(" 8. goto\n");
Console.Write("Choose one (q to quit): ");
do {
choice = (char) Console.Read();
} while(choice == '\n' | choice == '\r');
} while( choice < '1' | choice > '8' & choice != 'q');
(
---------- Post added at 07:19 PM ---------- Previous post was at 07:17 PM ----------
Notice that this loop now includes the break, continue, and goto statements. It also accepts
a q as a valid choice.
4. Expand the switch statement to include the break, continue, and goto statements, as
shown here:
case '6':
Console.WriteLine("The break:\n");
Console.WriteLine("break;");
break;
case '7':
Console.WriteLine("The continue:\n");
Console.WriteLine("continue;");
break;
case '8':
Console.WriteLine("The goto:\n");
Console.WriteLine("goto label;");
break;
5. Here is the entire Help3.cs program listing:
/*
The finished C# statement help system
that processes multiple requests.
*/
---------- Post added at 07:20 PM ---------- Previous post was at 07:19 PM ----------
using System;
class Help3 {
static void Main() {
char choice;
for(; {
do {
Console.WriteLine("Help on:");
Console.WriteLine(" 1. if");
Console.WriteLine(" 2. switch");
Console.WriteLine(" 3. for");
Console.WriteLine(" 4. while");
Console.WriteLine(" 5. do-while");
Console.WriteLine(" 6. break");
Console.WriteLine(" 7. continue");
Console.WriteLine(" 8. goto\n");
Console.Write("Choose one (q to quit): ");
do {
choice = (char) Console.Read();
} while(choice == '\n' | choice == '\r');
} while( choice < '1' | choice > '8' & choice != 'q');
if(choice == 'q') break;
---------- Post added at 07:24 PM ---------- Previous post was at 07:20 PM ----------
إني أحاول أن أشرح و أعطي أمثلة لما أنا بصدد شرحه و إنشاء الله أكون قد وفقت ولو بنسبة ظعيفة
---------- Post added at 07:25 PM ---------- Previous post was at 07:24 PM ----------
Console.WriteLine("\n");
switch(choice) {
case '1':
Console.WriteLine("The if:\n");
Console.WriteLine("if(condition) statement;");
Console.WriteLine("else statement;");
break;
case '2':
Console.WriteLine("The switch:\n");
Console.WriteLine("switch(expression) {");
Console.WriteLine(" case constant:");
Console.WriteLine(" statement sequence");
Console.WriteLine(" break;");
Console.WriteLine(" // ...");
Console.WriteLine("}");
break;
case '3':
Console.WriteLine("The for:\n");
Console.Write("for(init; condition; iteration)");
Console.WriteLine(" statement;");
break;
case '4':
Console.WriteLine("The while:\n");
Console.WriteLine("while(condition) statement;");
break;
case '5':
Console.WriteLine("The do-while:\n");
Console.WriteLine("do {");
Console.WriteLine(" statement;");
Console.WriteLine("} while (condition);");
break;
case '6':
Console.WriteLine("The break:\n");
Console.WriteLine("break;");
break;
case '7':
Console.WriteLine("The continue:\n");
Console.WriteLine("continue;");
break;
case '8':
Console.WriteLine("The goto:\n");
Console.WriteLine("goto label;");
break;
}
Console.WriteLine();
}
}
}
---------- Post added at 07:26 PM ---------- Previous post was at 07:25 PM ----------
Here is a sample run:
Help on:
1. if
2. switch
3. for
4. while
5. do-while
6. break
7. continue
8. goto
Choose one (q to quit): 1
The if:
if(condition) statement;
else statement;
Help on:
1. if
2. switch
3. for
4. while
5. do-while
6. break
7. continue
8. goto
---------- Post added at 07:32 PM ---------- Previous post was at 07:26 PM ----------
Choose one (q to quit): 6
The break:
break;
Help on:
1. if
2. switch
3. for
4. while
5. do-while
6. break
7. continue
8. goto
Choose one (q to quit): q
---------- Post added at 07:32 PM ---------- Previous post was at 07:32 PM ----------
As you have seen in some of the preceding examples, one loop can be nested inside another.
Nested loops are used to solve a wide variety of programming problems and are an essential
part of programming. So, before leaving the topic of C#’s loop statements, let’s look at one
more nested loop example. The following program uses a nested for loop to find the factors of
the numbers from 2 to 100:
// Use nested loops to find factors of numbers between 2 and 100.
using System;
class FindFac {
static void Main() {
for(int i=2; i <= 100; i++) {
Console.Write("Factors of " + i + ": ");
for(int j = 2; j <= i/2; j++)
if((i%j) == 0) Console.Write(j + " ");
Console.WriteLine();
}
}
}
Here is a portion of the output produced by the program:
Factors of 2:
Factors of 3:
Factors of 4: 2
Factors of 5:
Factors of 6: 2 3
Factors of 7:
Factors of 8: 2 4
Factors of 9: 3
Factors of 10: 2 5
Factors of 11:
Factors of 12: 2 3 4 6
Factors of 13:
Factors of 14: 2 7
Factors of 15: 3 5
Factors of 16: 2 4 8
Factors of 17:
Factors of 18: 2 3 6 9
Factors of 19:
Factors of 20: 2 4 5 10
In the program, the outer loop runs i from 2 through 100. The inner loop successively tests all
numbers from 2 up to i, printing those that evenly divide i.
---------- Post added at 07:35 PM ---------- Previous post was at 07:32 PM ----------
Chapter 3 Self Test
1. Write a program that reads characters from the keyboard until a period is received. Have the
program count the number of spaces. Report the total at the end of the program.
2. In the switch, can the code sequence from one case run into the next?
3. Show the general form of the if-else-if ladder.
4. Given
if(x < 10)
if(y > 100) {
if(!done) x = z;
else y = z;
}
else Console.WriteLine("error"); // what if?
with what if does the last else associate?
5. Show the for statement for a loop that counts from 1,000 to 0 by –2.
6. Is the following fragment valid?
for(int i = 0; i < num; i++)
sum += i;
count = i;
---------- Post added at 07:35 PM ---------- Previous post was at 07:35 PM ----------
10. The iteration expression in a for loop need not always alter the loop control variable by a
fixed amount. Instead, the loop control variable can change in any arbitrary way. Using this
concept, write a program that uses a for loop to generate and display the progression 1, 2, 4,
8, 16, 32, and so on.
11. The ASCII lowercase letters are separated from the uppercase letters by 32. Thus, to convert
a lowercase letter to uppercase, subtract 32 from it. Use this information to write a program
that reads characters from the keyboard. Have it convert all lowercase letters to uppercase,
and all uppercase letters to lowercase, displaying the result. Make no changes to any other
character. Have the program stop when the user presses the period key. At the end, have the
program display the number of case changes that have taken place.
---------- Post added at 07:36 PM ---------- Previous post was at 07:35 PM ----------
Chapter 4
Introducing Classes,
Objects, and Methods
---------- Post added at 07:37 PM ---------- Previous post was at 07:36 PM ----------
Key Skills & Concepts
● Class fundamentals
● Instantiate an object
● Method basics
● Method parameters
● Return a value from a method
● Constructors
● new
● Garbage collection
● Destructors
● The this keyword
Before you can go much further in your study of C#, you need to learn about the class. The
class is the essence of C# because it defines the nature of an object. As such, the class
forms the basis for object-oriented programming in C#. Within a class are defined data and
the code that acts upon that data. The code is contained in methods. Because classes, objects,
and methods are fundamental to C#, they are introduced in this chapter. Having a basic
understanding of these features will allow you to write more sophisticated programs and to
better understand certain key C# elements described in Chapter 5.
Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.
Class Fundamentals
We have been using classes since the start of this book. Of course, only extremely simple
classes have been used, and we have not taken advantage of the majority of their features. As
you will see, classes are substantially more powerful than the limited ones presented so far.
Let’s begin by reviewing the basics. A class is a template that defines the form of an object.
It typically specifies both code and data, with the code acting on the data. C# uses a class
specification to construct objects. Objects are instances of a class. Thus, a class is essentially a
set of plans that specify how to build an object. It is important to be clear on one issue: A class
is a logical abstraction. It is not until an object of that class has been created that a physical
representation of that class exists in memory.
One other point: Recall that the methods and variables that constitute a class are called
members of the class.
---------- Post added at 07:38 PM ---------- Previous post was at 07:37 PM ----------
The General Form of a Class
When you define a class, you declare the data that it contains and the code that operates on
it. While very simple classes might contain only code or only data, most real-world classes
contain both.
In general terms, data is contained in instance variables defined by the class, and code is
contained in methods. It is important to state at the outset, however, that C# defines several
specific flavors of members, which include instance variables, static variables, constants,
methods, constructors, destructors, indexers, events, operators, and properties. For now, we
will limit our discussion of the class to its essential elements: instance variables and methods.
Later in this chapter, constructors and destructors are discussed. The other types of members
are described in later chapters.
A class is created by using the keyword class. The general form of a class definition that
contains only instance variables and methods is shown here:
class classname {
// Declare instance variables.
access type var1;
access type var2;
// ...
access type varN;
// Declare methods.
access ret-type method1(parameters) {
// body of method
}
access ret-type method2(parameters) {
// body of method
}
// ...
access ret-type methodN(parameters) {
// body of method
}
}
Notice that each variable and method is preceded with access. Here, access is an access
specifier, such as public, which specifies how the member can be accessed. As mentioned in
Chapter 1, class members can be private to a class or more accessible. The access specifier
determines what type of access is allowed. The access specifier is optional and, if absent,
the member is private to the class. Members with private access can be used only by other
members of their class. For the examples in this chapter, all members (except for the Main( )
method) will be specified as public. This means they can be used by all other code—even code
defined outside the class. (The Main( ) method will continue to use the default access because
this is the currently recommended approach.) We will return to the topic of access specifiers in
a later chapter, after you have learned the fundamentals of the class.
Although there is no syntactic rule that enforces it, a well-designed class should define
one and only one logical entity. For example, a class that stores names and telephone numbers
will not normally also store information about the stock market, average rainfall, sunspot
cycles, or other unrelated information. The point here is that a well-designed class groups
logically connected information. Putting unrelated information into the same class will quickly
destructure your code!
Up to this point, the classes that we have been using have had only one method: Main( ).
Soon you will see how to create others. However, notice that the general form of a class does
not specify a Main( ) method. A Main( ) method is required only if that class is the starting
point for your program.
Define a Class
To illustrate classes, we will evolve a class that encapsulates information about vehicles,
such as cars, vans, and trucks. This class is called Vehicle, and it will store three items of
information about a vehicle: the number of passengers that it can carry, its fuel capacity, and its
average fuel consumption (in miles per gallon).
The first version of Vehicle is shown here. It defines three instance variables: Passengers,
FuelCap, and Mpg. Notice that Vehicle does not contain any methods. Thus, it is currently
a data-only class. (Subsequent sections will add methods to it.)
---------- Post added at 07:38 PM ---------- Previous post was at 07:38 PM ----------
class Vehicle {
public int Passengers; // number of passengers
public int FuelCap; // fuel capacity in gallons
public int Mpg; // fuel consumption in miles per gallon
}
The instance variables defined by Vehicle illustrate the way that instance variables are
declared in general. The general form for declaring an instance variable is shown here:
access type var-name;
Here, access specifies the access, type specifies the type of variable, and var-name is the
variable’s name. Thus, aside from the access specifier, you declare an instance variable in the
same way that you declare local variables. For Vehicle, the variables are preceded by the public
access modifier. As explained, this allows them to be accessed by code outside of Vehicle.
A class definition creates a new data type. In this case, the new data type is called Vehicle.
You will use this name to declare objects of type Vehicle. Remember that a class declaration is
only a type description; it does not create an actual object. Thus, the preceding code does not
cause any objects of type Vehicle to come into existence.
To actually create a Vehicle object, you will use a statement like the following:
Vehicle minivan = new Vehicle(); // create a Vehicle object called minivan
After this statement executes, minivan will be an instance of Vehicle. Thus, it will have
“physical” reality. For the moment, don’t worry about the details of this statement.
Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.
In this quest, C# is the current standard bearer. Created by Microsoft to support development
for its .NET Framework, C# leverages time-tested features with cutting-edge innovations and
provides a highly usable, efficient way to write programs for the modern enterprise computing
environment. In the course of this book, you will learn to program using it.
The purpose of this chapter is to introduce C#, including the forces that drove its creation,
its design philosophy, and several of its most important features. By far, the hardest thing
about learning a programming language is the fact that no element exists in isolation. Instead,
the components of the language work together. It is this interrelatedness that makes it difficult
to discuss one aspect of C# without involving others. To overcome this problem, this chapter
provides a brief overview of several C# features, including the general form of a C# program,
two control statements, and several operators. It does not go into too many details, but rather
concentrates on the general concepts common to any C# program.
At this time, version 3.0 is the current release of C#, and this is the version taught in this
book. Of course, much of the information presented here applies to all versions of C#.
C#’s Family Tree
Computer languages do not exist in a void. Rather, they relate to one another, with each new
language influenced in one form or another by the ones that came before. In a process akin
to cross-pollination, features from one language are adapted by another, a new innovation is
integrated into an existing context, or an older construct is removed. In this way, languages
evolve and the art of programming advances. C# is no exception.
---------- Post added at 08:43 PM ---------- Previous post was at 08:39 PM ----------
السلام عايكم اخي الكريم انا مبتدئ في هدا المجال
Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.
Each time you create an instance of a class, you are creating an object that contains its own
copy of each instance variable defined by the class. Thus, every Vehicle object will contain
its own copies of the instance variables Passengers, FuelCap, and Mpg. To access these
variables, you will use the member access operator, which is a period. It is commonly referred
to as the dot operator. The dot operator links the name of an object with the name of a member.
The general form of the dot operator is shown here:
object.member
Thus, the object is specified on the left, and the member is put on the right. For example, to
assign the FuelCap variable of minivan the value 16, use the following statement:
minivan.FuelCap = 16;
In general, you can use the dot operator to access both instance variables and methods.
Here is a complete program that uses the Vehicle class:
/* A program that uses the Vehicle class.
Call this file UseVehicle.cs
*/
---------- Post added at 07:52 PM ---------- Previous post was at 07:50 PM ----------
using System;
// A class that encapsulates information about vehicles.
class Vehicle {
public int Passengers; // number of passengers
public int FuelCap; // fuel capacity in gallons
public int Mpg; // fuel consumption in miles per gallon
}
// This class declares an object of type Vehicle.
class VehicleDemo {
static void Main() {
Vehicle minivan = new Vehicle();
int range;
// Assign values to fields in minivan.
minivan.Passengers = 7;
minivan.FuelCap = 16;
minivan.Mpg = 21;
// Compute the range assuming a full tank of gas.
range = minivan.FuelCap * minivan.Mpg;
Console.WriteLine("Minivan can carry " + minivan.Passengers +
" with a range of " + range);
}
}
---------- Post added at 07:52 PM ---------- Previous post was at 07:52 PM ----------
This program consists of two classes: Vehicle and VehicleDemo. Inside VehicleDemo, the
Main( ) method creates an instance of Vehicle called minivan. Then the code within Main( )
accesses the instance variables associated with minivan, assigning them values and using
those values. It is important to understand that Vehicle and VehicleDemo are two separate
classes. The only relationship they have to each other is that one class creates an instance
of the other. Although they are separate classes, code inside VehicleDemo can access the
members of Vehicle because they are declared public. If they had not been given the public
access specifier, their access would have been limited to the Vehicle class, and VehicleDemo
would not have been able to use them.
Assuming that you call the preceding file UseVehicle.cs, compiling this program creates
a file called UseVehicle.exe. Both the Vehicle and VehicleDemo classes are automatically part
of the executable file. The program displays the following output:
Minivan can carry 7 with a range of 336
It is not necessary for both the Vehicle and the VehicleDemo classes to actually be in the
same source file. You could put each class in its own file, called Vehicle.cs and VehicleDemo.cs,
for example. Just tell the C# compiler to compile both files and link them together. For
example, you could use this command line to compile the program if you split it into two
pieces as just described:
---------- Post added at 08:02 PM ---------- Previous post was at 07:52 PM ----------
csc Vehicle.cs VehicleDemo.cs
This will create VehicleDemo.exe because that is the class that contains the Main( ) method.
If you are using the Visual Studio IDE, you will need to add both files to your project and
then build.
Before moving on, let’s review a fundamental principle: Each object has its own copies of
the instance variables defined by its class. Thus, the contents of the variables in one object can
differ from the contents of the variables in another. There is no connection between the two
objects, except for the fact that they are both objects of the same type. For example, if you have
two Vehicle objects, each has its own copy of Passengers, FuelCap, and Mpg, and the contents
of these can differ between the two objects. The following program demonstrates this fact:
// This program creates two Vehicle objects.
using System;
// A class that encapsulates information about vehicles.
class Vehicle {
public int Passengers; // number of passengers
public int FuelCap; // fuel capacity in gallons
public int Mpg; // fuel consumption in miles per gallon
}
// This class declares two objects of type Vehicle.
class TwoVehicles {
---------- Post added at 08:03 PM ---------- Previous post was at 08:02 PM ----------
static void Main() {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
int range1, range2;
// Assign values to fields in minivan.
minivan.Passengers = 7;
minivan.FuelCap = 16;
minivan.Mpg = 21;
// Assign values to fields in sportscar.
sportscar.Passengers = 2;
sportscar.FuelCap = 14;
sportscar.Mpg = 12;
// Compute the ranges assuming a full tank of gas.
range1 = minivan.FuelCap * minivan.Mpg;
range2 = sportscar.FuelCap * sportscar.Mpg;
Console.WriteLine("Minivan can carry " + minivan.Passengers +
" with a range of " + range1);
Console.WriteLine("Sportscar can carry " + sportscar.Passengers +
" with a range of " + range2);
}
}
---------- Post added at 08:08 PM ---------- Previous post was at 08:03 PM ----------
The output produced by this program is shown here:
Minivan can carry 7 with a range of 336
Sportscar can carry 2 with a range of 168
As you can see, minivan’s data is completely separate from the data contained in sportscar.
---------- Post added at 08:25 PM ---------- Previous post was at 08:08 PM ----------
How Objects Are Created
In the preceding programs, the following line was used to create an object of type Vehicle:
Vehicle minivan = new Vehicle();
This declaration performs three functions. First, it declares a variable called minivan of the
class type Vehicle. This variable is not, itself, an object. Instead, it is simply a variable that can
refer to an object. Second, the declaration creates an actual, physical instance of the object.
This is done by using the new operator. Finally, it assigns to minivan a reference to that
object. Thus, after the line executes, minivan refers to an object of type Vehicle.
The new operator dynamically allocates (that is, allocates at runtime) memory for an
object and returns a reference to it. This reference is then stored in a variable. Thus, in C#, all
class objects must be dynamically allocated.
As you might expect, it is possible to separate the declaration of minivan from the creation
of the object to which it will refer, as shown here:
Vehicle minivan; // declare a reference to an object
minivan = new Vehicle(); // allocate a Vehicle object
The first line declares minivan as a reference to an object of type Vehicle. Thus, minivan is
a variable that can refer to an object, but it is not an object itself. The next line creates a new
Vehicle object and assigns a reference to it to minivan. Now, minivan is linked with an object.
The fact that class objects are accessed through a reference explains why classes are called
reference types. The key difference between value types and reference types is what a variable
of each type means. For a variable of a value type, the variable itself contains the value. For
example, given
int x;
x = 10;
---------- Post added at 08:39 PM ---------- Previous post was at 08:25 PM ----------
x contains the value 10 because x is a variable of type int, which is a value type. However, in
the case of
Vehicle minivan = new Vehicle();
minivan does not, itself, contain the object. Instead, it contains a reference to the object.
Reference Variables and Assignment
In an assignment operation, reference variables act differently than do variables of a value
type, such as int. When you assign one value type variable to another, the situation is
straightforward. The variable on the left receives a copy of the value of the variable on the
right. When you assign one object reference variable to another, the situation is a bit more
complicated because you are causing the variable on the left to refer to the object referred
---------- Post added at 08:40 PM ---------- Previous post was at 08:39 PM ----------
to by the variable on the right. The effect of this difference can cause some counterintuitive
results. For example, consider the following fragment:
Vehicle car1 = new Vehicle();
Vehicle car2 = car1;
At first glance, it is easy to think that car1 and car2 refer to different objects, but this is not the
case. Instead, car1 and car2 will both refer to the same object. The assignment of car1 to car2
simply makes car2 refer to the same object as does car1. Thus, the object can be acted upon
by either car1 or car2. For example, after this assignment executes,
car1.Mpg = 26;
both of these WriteLine( ) statements display the same value, 26:
Console.WriteLine(car1.Mpg);
Console.WriteLine(car2.Mpg);
Although car1 and car2 both refer to the same object, they are not linked in any other way.
For example, a subsequent assignment to car2 simply changes what object car2 refers to. For
example:
Vehicle car1 = new Vehicle();
Vehicle car2 = car1;
Vehicle car3 = new Vehicle();
Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.
السلام عليكم أخي الكريم شكرا لك اخي الكريم بارك الله فيك الموضوع ممتاز لاكن ياليت لو كان مترجم إلي العربية و الله أعلم و الله الموفق
Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.
car2 = car3; // now car2 and car3 refer to the same object.
After this sequence executes, car2 refers to the same object as car3. Of course, car1 continues
to refer to its original object.
Methods
As explained, instance variables and methods are two of the primary constituents of classes. So
far, the Vehicle class contains data, but no methods. Although data-only classes are perfectly
valid, most classes will have methods. Methods are subroutines that manipulate the data
defined by the class and, in many cases, provide access to that data. Typically, other parts of
your program will interact with a class through its methods.
A method contains one or more statements. In well-written C# code, each method performs
only one task. Each method has a name, and this name is used to call the method. In general,
you can name a method using any valid identifier that you please. However, remember that
Main( ) is reserved for the method that begins execution of your program. Also, don’t use C#’s
keywords for method names.
When denoting methods in text, this book has used and will continue to use a convention
that has become common when writing about C#. A method will have parentheses after its
name. For example, if a method’s name is GetVal, it will be written GetVal( ) when its name
---------- Post added at 10:39 AM ---------- Previous post was at 10:36 AM ----------
is used in a sentence. This notation will help you distinguish variable names from method
names in this book.
The general form of a method is shown here:
access ret-type name(parameter-list) {
// body of method
}
Here, access is an access modifier that governs what other parts of your program can call the
method. As explained earlier, the access modifier is optional. If not present, the method is private
to the class in which it is declared. For now, we will declare methods public so that they can be
called by any other code in the program. The ret-type specifies the type of data returned by the
method. This can be any valid type, including class types that you create. If the method does
not return a value, its return type must be void. The name of the method is specified by name.
This can be any legal identifier other than those which would cause conflicts within the current
declaration space. The parameter-list is a sequence of type and identifier pairs separated by
commas. Parameters are essentially variables that receive the value of the arguments passed to
the method when it is called. If the method has no parameters, the parameter list will be empty.
---------- Post added at 10:41 AM ---------- Previous post was at 10:39 AM ----------
Add a Method to the Vehicle Class
As just explained, the methods of a class typically manipulate and provide access to the data
of the class. With this in mind, recall that Main( ) in the preceding examples computed the range
of a vehicle by multiplying its fuel consumption rate by its fuel capacity. While technically
correct, this is not the best way to handle this computation. The calculation of a vehicle’s range is
something that is best handled by the Vehicle class itself. The reason for this conclusion is easy
to understand: The range of a vehicle is dependent upon the capacity of the fuel tank and the
rate of fuel consumption, and both of these quantities are encapsulated by Vehicle. By adding a
method to Vehicle that computes the range, you are enhancing its object-oriented structure.
To add a method to Vehicle, specify it within Vehicle’s declaration. For example, the following
version of Vehicle contains a method called Range( ) that displays the range of the vehicle:
// Add range to Vehicle.
using System;
// A class that encapsulates information about vehicles.
class Vehicle {
public int Passengers; // number of passengers
public int FuelCap; // fuel capacity in gallons
public int Mpg; // fuel consumption in miles per gallon
// Display the range.
public void Range() {
Console.WriteLine("Range is " + FuelCap * Mpg);
}
}
Notice that FuelCap and Mpg are used
directly, without the dot operator.
---------- Post added at 10:45 AM ---------- Previous post was at 10:41 AM ----------
class AddMeth {
static void Main() {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
// Assign values to fields in minivan.
minivan.Passengers = 7;
minivan.FuelCap = 16;
minivan.Mpg = 21;
// Assign values to fields in sportscar.
sportscar.Passengers = 2;
sportscar.FuelCap = 14;
sportscar.Mpg = 12;
Console.Write("Minivan can carry " + minivan.Passengers +
". ");
minivan.Range(); // display range of minivan
Console.Write("Sportscar can carry " + sportscar.Passengers +
". ");
sportscar.Range(); // display range of sportscar.
}
}
This program generates the following output:
Minivan can carry 7. Range is 336
Sportscar can carry 2. Range is 168
---------- Post added at 10:49 AM ---------- Previous post was at 10:45 AM ----------
Let’s look at the key elements of this program, beginning with the Range( ) method itself.
The first line of Range( ) is
public void Range() {
This line declares a method called Range that has no parameters. It is specified as public, so it
can be used by all other parts of the program. Its return type is void. Thus, Range( ) does not
return a value to the caller. The line ends with the ****ing curly brace of the method body.
The body of Range( ) consists solely of this line:
Console.WriteLine("Range is " + FuelCap * Mpg);
This statement displays the range of the vehicle by multiplying FuelCap by Mpg. Since each
object of type Vehicle has its own copy of FuelCap and Mpg, when Range( ) is called, the
range computation uses the calling object’s copies of those variables.
---------- Post added at 11:12 AM ---------- Previous post was at 10:49 AM ----------
The Range( ) method ends when its closing curly brace is encountered. This causes
program control to transfer back to the caller.
Next, look closely at this line of code from inside Main( ):
minivan.Range();
This statement invokes the Range( ) method on minivan. That is, it calls Range( ) relative
to the object referred to by minivan, by use of the dot operator. When a method is called,
program control is transferred to the method. When the method terminates, control is
transferred back to the caller, and execution resumes with the line of code following the call.
In this case, the call to minivan.Range( ) displays the range of the vehicle defined by
minivan. In a similar fashion, the call to sportscar.Range( ) displays the range of the vehicle
defined by sportscar. Each time Range( ) is invoked, it displays the range for the specified object.
There is something very important to notice inside the Range( ) method: The instance
variables FuelCap and Mpg are referred to directly, without use of the dot operator. When
a method uses an instance variable that is defined by its class, it does so directly, without
explicit reference to an object and without use of the dot operator. This is easy to understand
if you think about it. A method is always invoked relative to some object of its class. Once
this invocation has occurred, the object is known. Thus, within a method, there is no need
to specify the object a second time. This means that FuelCap and Mpg inside Range( )
implicitly refer to the copies of those variables found in the object that invokes Range( ).
---------- Post added at 11:14 AM ---------- Previous post was at 11:12 AM ----------
Return from a Method
In general, there are two conditions that cause a method to return. The first, as the Range( )
method in the preceding example shows, occurs when the method’s closing curly brace is
encountered. The second is when a return statement is executed. There are two forms of
return: one for use in void methods (those that do not return a value) and one for returning
values. The first form is examined here. The next section explains how to return values.
In a void method, you can cause the immediate termination of a method by using this form
of return:
return ;
When this statement executes, program control returns to the caller, skipping any remaining
code in the method. For example, consider this method:
public void MyMeth() {
int i;
for(i=0; i<10; i++) {
if(i == 5) return; // stop at 5
Console.WriteLine(i);
}
}
Here, the for loop will only run from 0 to 5, because once i equals 5, the method returns.
---------- Post added at 11:14 AM ---------- Previous post was at 11:14 AM ----------
It is permissible to have multiple return statements in a method, especially when there are
two or more routes out of it. For example,
public void MyMeth() {
// ...
if(done) return;
// ...
if(error) return;
}
Here, the method returns if it is done or if an error occurs. Be careful, however, because having
too many exit points in a method can destructure your code, so avoid using them casually.
To review: A void method can return in one of two ways: its closing curly brace is reached,
or a return statement is executed.
Though trading on financial markets involves high risk, it can still generate extra income in case you apply the right approach. By choosing a reliable broker such as InstaForex you get access to the international financial markets and open your way towards financial independence. You can sign up here.
Threads
Posts
Members