TERM

NONE of the CONTENT IS OWNED BY ME

BlogSpot SEO Tips: Best On-Page SEO Strategies for Bloggers

What if you can get traffic from search engines as WordPress blogs to your BlogSpot blog?Same traffic. Same People. Same conversion rates?But, Unlike WordPress blog users..

How to Create a Free Blog using Blogspot.com with Images

Do you want to create a blog using BlogSpot blogging platform? Not found a great guide on creating a blog on BlogSpot?

How to Set up Custom Domain Name for Blogger Blogs

The internet has become a more open place to everyone. Anyone can share their skills, knowledge and ideas through various mediums such as Videos, podcast and obviously through blogging.

Best Responsive Premium Blogger Templates

No doubt that Blogger is a great blogging platform for both beginners and professionals. Many pro bloggers such as Darren Rowse, Amit Agarwal and Harsh Agrawal have started their blogging journey first on Blogger.

How to Submit Your Website to Search Engines

The fundamental step to boost traffic to your site is the ranking your website on search engine result pages in higher places. To rank your site on the top of search engines,

Wednesday 4 March 2015

Lesson 4: Control Statements - Loops In the last lesson, you learned how to create a simple loop by using the goto statement. I advised you that this is not the best way to perform loops in C#. The information in this lesson will teach you the proper way to execute iterative logic with the various C# looping statements. Its goal is to meet the following objectives: Learn the while loop. Learn the do loop. Learn the for loop. Learn the foreach loop. Complete your knowledge of the break statement. Teach you how to use the continue statement. The while Loop A while loop will check a condition and then continues to execute a block of code as long as the condition evaluates to a boolean value of true. Its syntax is as follows: while () { }. The statements can be any valid C# statements. The boolean expression is evaluated before any code in the following block has executed. When the boolean expression evaluates to true, the statements will execute. Once the statements have executed, control returns to the beginning of the while loop to check the boolean expression again. When the boolean expression evaluates to false, the while loop statements are skipped and execution begins after the closing brace of that block of code. Before entering the loop, ensure that variables evaluated in the loop condition are set to an initial state. During execution, make sure you update variables associated with the boolean expression so that the loop will end when you want it to. Listing 4-1 shows how to implement a while loop. Listing 4-1. The While Loop: WhileLoop.cs using System; class WhileLoop { public static void Main() { int myInt = 0; while (myInt < 10) { Console.Write("{0} ", myInt); myInt++; } Console.WriteLine(); } } Listing 4-1 shows a simple while loop. It begins with the keyword while, followed by a boolean expression. All control statements use boolean expressions as their condition for entering/continuing the loop. This means that the expression must evaluate to either a true or false value. In this case we are checking the myInt variable to see if it is less than (<) 10. Since myInt was initialized to 0, the boolean expression will return true the first time it is evaluated. When the boolean expression evaluates to true, the block immediately following the boolean expression will be executed. Within the while block we print the number and a space to the console. Then we increment (++) myInt to the next integer. Once the statements in the while block have executed, the boolean expression is evaluated again. This sequence will continue until the boolean expression evaluates to false. Once the boolean expression is evaluated as false, program control will jump to the first statement following the while block. In this case, we will write the numbers 0 through 9 to the console, exit the while block, and print a new line to the console. The do Loop A do loop is similar to the while loop, except that it checks its condition at the end of the loop. This means that the do loop is guaranteed to execute at least one time. On the other hand, a while loop evaluates its boolean expression at the beginning and there is generally no guarantee that the statements inside the loop will be executed, unless you program the code to explicitly do so. One reason you may want to use a do loop instead of a while loop is to present a message or menu such as the one in Listing 4-2 and then retrieve input from a user. Listing 4-2. The Do Loop: DoLoop.cs using System; class DoLoop { public static void Main() { string myChoice; do { // Print A Menu Console.WriteLine("My Address Book\n"); Console.WriteLine("A - Add New Address"); Console.WriteLine("D - Delete Address"); Console.WriteLine("M - Modify Address"); Console.WriteLine("V - View Addresses"); Console.WriteLine("Q - Quit\n"); Console.WriteLine("Choice (A,D,M,V,or Q): "); // Retrieve the user's choice myChoice = Console.ReadLine(); // Make a decision based on the user's choice switch(myChoice) { case "A": case "a": Console.WriteLine("You wish to add an address."); break; case "D": case "d": Console.WriteLine("You wish to delete an address."); break; case "M": case "m": Console.WriteLine("You wish to modify an address."); break; case "V": case "v": Console.WriteLine("You wish to view the address list."); break; case "Q": case "q": Console.WriteLine("Bye."); break; default: Console.WriteLine("{0} is not a valid choice", myChoice); break; } // Pause to allow the user to see the results Console.Write("press Enter key to continue..."); Console.ReadLine(); Console.WriteLine(); } while (myChoice != "Q" && myChoice != "q"); // Keep going until the user wants to quit } } Listing 4-2 shows a do loop in action. The syntax of the do loop is do { } while ();. The statements can be any valid C# programming statements you like. The boolean expression is the same as all others we've encountered so far. It returns either true or false. In the Main method, we declare the variable myChoice of type string. Then we print a series of statements to the console. This is a menu of choices for the user. We must get input from the user, which is in the form of a Console.ReadLine method which returns the user's value into the myChoice variable. We must take the user's input and process it. A very efficient way to do this is with a switch statement. Notice that we've placed matching upper and lower case letters together to obtain the same functionality. This is the only legal way to have automatic fall through between cases. If you were to place any statements between two cases, you would not be able to fall through. Another point is that we used the default: case, which is a very good habit for the reasons stated in Lesson 3: Control Statements - Selection. The for Loop A for loop works like a while loop, except that the syntax of the for loop includes initialization and condition modification. for loops are appropriate when you know exactly how many times you want to perform the statements within the loop. The contents within the for loop parentheses hold three sections separated by semicolons (; ; ) { }. The initializer list is a comma separated list of expressions. These expressions are evaluated only once during the lifetime of the for loop. This is a one-time operation, before loop execution. This section is commonly used to initialize an integer to be used as a counter. Once the initializer list has been evaluated, the for loop gives control to its second section, the boolean expression. There is only one boolean expression, but it can be as complicated as you like as long as the result evaluates to true or false. The boolean expression is commonly used to verify the status of a counter variable. When the boolean expression evaluates to true, the statements within the curly braces of the for loop are executed. After executing for loop statements, control moves to the top of loop and executes the iterator list, which is normally used to increment or decrement a counter. The iterator list can contain a comma separated list of statements, but is generally only one statement. Listing 4-3 shows how to implement a for loop. The purpose of the program is to print only odd numbers less than 10. Listing 4-3. The For Loop: ForLoop.cs using System; class ForLoop { public static void Main() { for (int i=0; i < 20; i++) { if (i == 10) break; if (i % 2 == 0) continue; Console.Write("{0} ", i); } Console.WriteLine(); } } Normally, for loop statements execute from the opening curly brace to the closing curly brace without interruption. However, in Listing 4-3, we've made a couple exceptions. There are a couple if statements disrupting the flow of control within the for block. The first if statement checks to see if i is equal to 10. Now you see another use of the break statement. Its behavior is similar to the selection statements, as discussed in Lesson 3: Control Statements - Selection. It simply breaks out of the loop at that point and transfers control to the first statement following the end of the for block. The second if statement uses the remainder operator to see if i is a multiple of 2. This will evaluate to true when i is divided by 2 with a remainder equal to zero, (0). When true, the continue statement is executed, causing control to skip over the remaining statements in the loop and transfer back to the iterator list. By arranging the statements within a block properly, you can conditionally execute them based upon whatever condition you need. When program control reaches either a continue statement or end of block, it transfers to the third section within the for loop parentheses, the iterator list. This is a comma separated list of actions that are executed after the statements in the for block have been executed. Listing 4-3 is a typical action, incrementing the counter. Once this is complete, control transfers to the boolean expression for evaluation. Similar to the while loop, a for loop will continue as long as the boolean expression is true. When the boolean expression becomes false, control is transferred to the first statement following the for block. For this tutorial, I chose to implement break and continue statements in Listing 4-3 only. However, they may be used in any of the loop statements. The foreach Loop A foreach loop is used to iterate through the items in a list. It operates on arrays or collections such as ArrayList, which can be found in the System.Collections namespace. The syntax of a foreach loop is foreach ( in ) { }. The type is the type of item contained in the list. For example, if the type of the list was int[] then the type would be int. The iteration variable is an identifier that you choose, which could be anything but should be meaningful. For example, if the list contained an array of people's ages, then a meaningful name for item name would be age. The in keyword is required. As mentioned earlier, the list could be either an array or a collection. You learned about arrays in Lesson 02: Operators, Types, and Variables. You can also iterate over C# generic collections also, described in Lesson 20: Introduction to Generic Collections. While iterating through the items of a list with a foreach loop, the list is read-only. This means that you can't modify the iteration variable within a foreach loop. There is a subtlety here; Later, you'll learn how to create custom types, called class and struct, that can contain multiple fields. You can change the fields of the class or struct, but not the iteration variable for the class or struct itself in a foreach loop. On each iteration through a foreach loop the list is queried for a new value. As long as the list can return a value, this value will be put into the read-only iteration variable, causing the statements in the foreach block to be executed. When the collection has been fully traversed, control will transfer to the first executable statement following the end of the foreach block. Listing 4-4 demonstrates how to use a foreach loop. Listing 4-4. The ForEach Loop: ForEachLoop.cs using System; class ForEachLoop { public static void Main() { string[] names = {"Cheryl", "Joe", "Matt", "Robert"}; foreach (string person in names) { Console.WriteLine("{0} ", person); } } } In Listing 4-4, the first thing we've done inside the Main method is declare and initialize the names array with 4 strings. This is the list used in the foreach loop. In the foreach loop, we've used a string variable, person, as the item name, to hold each element of the names array. As long as there are names in the array that have not been returned, the Console.WriteLine method will print each value of the person variable to the screen. Summary Loops allow you to execute a block of statements repeatedly. C# offers several statements to construct loops with, including the while, do, for, and foreach loops. while loops execute a block of statements as long as an expression is true, do loops execute a block of statements at least once and then keep going as long as a condition is true, for loops execute a block of statements a specified amount of times, and foreach loops execute a block of statements for each item in a collection. Normally a block of statements will execute from beginning to end. However, the normal flow of a loop can be changed with the break and continue statements. So far, the only method you've seen in this tutorial is the Main method, which is the entry point of a C# application. However, you are probably wanting to write larger programs to test your new knowledge. This requires breaking up the code into methods to keep it organized and logical. For this, I invite you to return for Lesson 5: Introduction to Methods, where you can learn new techniques of organizing your code.

Lesson 3: Control Statements - Selection In the last couple of lessons, every program you saw contained a limited amount of sequential steps and then stopped. There were no decisions you could make with the input and the only constraint was to follow straight through to the end. The information in this lesson will help you branch into separate logical sequences based on decisions you make. More specifically, the goals of this lesson are as follows: Learn the if statements. Learn the switch statement. Learn how break is used in switch statements. Understand proper use of the goto statement. The if Statement An if statement allows you to take different paths of logic, depending on a given condition. When the condition evaluates to a boolean true, a block of code for that true condition will execute. You have the option of a single if statement, multiple else if statements, and an optional else statement. Listing 3-1 shows how each of these types of if statements work. Listing 3-1. forms of the if statement: IfSelection.cs using System; class IfSelect { public static void Main() { string myInput; int myInt; Console.Write("Please enter a number: "); myInput = Console.ReadLine(); myInt = Int32.Parse(myInput); // Single Decision and Action with braces if (myInt > 0) { Console.WriteLine("Your number {0} is greater than zero.", myInt); } // Single Decision and Action without brackets if (myInt < 0) Console.WriteLine("Your number {0} is less than zero.", myInt); // Either/Or Decision if (myInt != 0) { Console.WriteLine("Your number {0} is not equal to zero.", myInt); } else { Console.WriteLine("Your number {0} is equal to zero.", myInt); } // Multiple Case Decision if (myInt < 0 || myInt == 0) { Console.WriteLine("Your number {0} is less than or equal to zero.", myInt); } else if (myInt > 0 && myInt <= 10) { Console.WriteLine("Your number {0} is in the range from 1 to 10.", myInt); } else if (myInt > 10 && myInt <= 20) { Console.WriteLine("Your number {0} is in the range from 11 to 20.", myInt); } else if (myInt > 20 && myInt <= 30) { Console.WriteLine("Your number {0} is in the range from 21 to 30.", myInt); } else { Console.WriteLine("Your number {0} is greater than 30.", myInt); } } } The statements in Listing 3-1 use the same input variable, myInt as a part of their evaluations. This is another way of obtaining interactive input from the user. Here's the pertinent code: Console.Write("Please enter a number: "); myInput = Console.ReadLine(); myInt = Int32.Parse(myInput); We first print the line "Please enter a number: " to the console. The Console.ReadLine() statement causes the program to wait for input from the user, who types a number and then presses Enter. This number is returned in the form of a string into the myInput variable, which is a string type. Since we must evaluate the user's input in the form of an int, myInput must be converted. This is done with the command Int32.Parse(myInput). (Int32 and similar types will be covered in another lesson on advanced types) The result is placed into the myInt variable, which is an int type. Now that we have a variable in the type we wanted, we will evaluate it with if statements. The first statement is of the form if (boolean expression) { statements }, as shown below: // Single Decision and Action with braces if (myInt > 0) { Console.WriteLine("Your number {0} is greater than zero.", myInt); } You must begin with the keyword if. Next is the boolean expression between parenthesis. This boolean expression must evaluate to a true or false value. In this case, we are checking the user's input to see if it is greater than (>) 0. If this expression evaluates to true, we execute the statements within the curly braces. (We refer to the structure with curly braces as a "block") There could be one or more statements within this block. If the boolean expression evaluates to false, we ignore the statements inside the block and continue program execution with the next statement after the block. Note: In other languages, such as C and C++, conditions can be evaluated where a result of 0 is false and any other number is true. In C#, the condition must evaluate to a boolean value of either true or false. If you need to simulate a numeric condition with C#, you can do so by writing it as (myInt != 0), which means that the expression evaluates to true if myInt is not 0. The second if statement is much like the first, except it does not have a block, as shown here: // Single Decision and Action without braces if (myInt < 0) Console.WriteLine("Your number {0} is less than zero.", myInt); If its boolean expression evaluates to true, the first statement after the boolean expression will be executed. When the boolean expression evaluates to false, the first statement after the boolean expression will be skipped and the next program statement will be executed. This form of if statement is adequate when you only have a single statement to execute. If you want to execute two or more statements when the boolean expression evaluates to true, you must enclose them in a block. Most of the time, you'll want to make an either/or kind of decision. This is called an if/else statement. The third if statement in Listing 3-1 presents this idea, as shown below: // Either/Or Decision if (myInt != 0) { Console.WriteLine("Your number {0} is not equal to zero.", myInt); } else { Console.WriteLine("Your number {0} is equal to zero.", myInt); } When the boolean expression evaluates to true, the statement(s) in the block immediately following the if statement are executed. However, when the boolean expression evaluates to false, the statements in the block following the else keyword are executed. When you have multiple expressions to evaluate, you can use the if/else if/else form of the if statement. We show this form in the fourth if statement of Listing 3-1, and repeated below: // Multiple Case Decision if (myInt < 0 || myInt == 0) { Console.WriteLine("Your number {0} is less than or equal to zero.", myInt); } else if (myInt > 0 && myInt <= 10) { Console.WriteLine("Your number {0} is in the range from 1 to 10.", myInt); } else if (myInt > 10 && myInt <= 20) { Console.WriteLine("Your number {0} is in the range from 11 to 20.", myInt); } else if (myInt > 20 && myInt <= 30) { Console.WriteLine("Your number {0} is in the range from 21 to 30.", myInt); } else { Console.WriteLine("Your number {0} is greater than 30.", myInt); } This example begins with the if keyword, again executing the following block if the boolean expression evaluates to true. However, this time you can evaluate multiple subsequent conditions with the else if keyword combination. the else if statement also takes a boolean expression, just like the if statement. The rules are the same, when the boolean expression for the else if statement evaluates to true, the block immediately following the boolean expression is executed. When none of the other if or else if boolean expressions evaluate to true, the block following the else keyword will be executed. Only one section of an if/else if/else statement will be executed. One difference in the last statement from the others is the boolean expressions. The boolean expression, (myInt < 0 || myInt == 0), contains the conditional OR (||) operator. In both the regular OR (|) operator and the conditional OR (||) operator, the boolean expression will evaluate to true if either of the two sub-expressions on either side of the operator evaluate to true. The primary difference between the two OR forms are that the regular OR operator will evaluate both sub-expressions every time. However, the conditional OR will evaluate the second sub-expression only if the first sub-expression evaluates to false. The boolean expression, (myInt > 0 && myInt <= 10), contains the conditional AND operator. Both the regular AND (&) operator and the conditional AND (&&) operator will return true when both of the sub-expressions on either side of the operator evaluate to true. The difference between the two is that the regular AND operator will evaluate both expressions every time. However, the conditional AND operator will evaluate the second sub-expression only when the first sub-expression evaluates to true. The conditional operators (&& and ||) are commonly called short-circuit operators because they do not always evaluate the entire expression. Thus, they are also used to produce more efficient code by ignoring unnecessary logic. The switch Statement Another form of selection statement is the switch statement, which executes a set of logic depending on the value of a given parameter. The types of the values a switch statement operates on can be booleans, enums, integral types, and strings. Lesson 2: Operators, Types, and Variables discussed the bool type, integral types and strings and Lesson 17: Enums will teach you what an enum type is. Listing 3-2 shows how to use the switch statement with both int and string types. Listing 3-2. Switch Statements: SwitchSelection.cs using System; class SwitchSelect { public static void Main() { string myInput; int myInt; begin: Console.Write("Please enter a number between 1 and 3: "); myInput = Console.ReadLine(); myInt = Int32.Parse(myInput); // switch with integer type switch (myInt) { case 1: Console.WriteLine("Your number is {0}.", myInt); break; case 2: Console.WriteLine("Your number is {0}.", myInt); break; case 3: Console.WriteLine("Your number is {0}.", myInt); break; default: Console.WriteLine("Your number {0} is not between 1 and 3.", myInt); break; } decide: Console.Write("Type \"continue\" to go on or \"quit\" to stop: "); myInput = Console.ReadLine(); // switch with string type switch (myInput) { case "continue": goto begin; case "quit": Console.WriteLine("Bye."); break; default: Console.WriteLine("Your input {0} is incorrect.", myInput); goto decide; } } } Note: Listing 3-2 will throw an exception if you enter any value other than an int. i.e. the letter 'a' would be an error. You can visit Lesson 15: Introduction to Exception Handling to learn more about how to anticipate and handle these type of problems. Listing 3-2 shows a couple of switch statements. The switch statement begins with the switch keyword followed by the switch expression. In the first switch statement in listing 3-2, the switch expression evaluates to an int type, as follows: // switch with integer type switch (myInt) { case 1: Console.WriteLine("Your number is {0}.", myInt); break; case 2: Console.WriteLine("Your number is {0}.", myInt); break; case 3: Console.WriteLine("Your number is {0}.", myInt); break; default: Console.WriteLine("Your number {0} is not between 1 and 3.", myInt); break; } The switch block follows the switch expression, where one or more choices are evaluated for a possible match with the switch expression. Each choice is labeled with the case keyword, followed by an example that is of the same type as the switch expression and followed by a colon (:). In the example we have case 1:, case 2:, and case 3:. When the result evaluated in the switch expression matches one of these choices, the statements immediately following the matching choice are executed, up to and including a branching statement, which could be either a break, continue, goto , return, or throw statement. table 3-1 summarizes the branching statements. Table 3-1. C# Branching Statements Branching statement Description break Leaves the switch block continue Leaves the switch block, skips remaining logic in enclosing loop, and goes back to loop condition to determine if loop should be executed again from the beginning. Works only if switch statement is in a loop as described in Lesson 04: Control Statements - Loops. goto Leaves the switch block and jumps directly to a label of the form ":" return Leaves the current method. Methods are described in more detail in Lesson 05: Methods. throw Throws an exception, as discussed in Lesson 15: Introduction to Exception Handling. You may also include a default choice following all other choices. If none of the other choices match, then the default choice is taken and its statements are executed. Although use of the default label is optional, I highly recommend that you always include it. This will help catch unforeseen circumstances and make your programs more reliable. Each case label must end with a branching statement, as described in table 3-1, which is normally the break statement. The break statement will cause the program to exit the switch statement and begin execution with the next statement after the switch block. There are two exceptions to this: adjacent case statements with no code in between or using a goto statement. Here's an example that shows how to combine case statements: switch (myInt) { case 1: case 2: case 3: Console.WriteLine("Your number is {0}.", myInt); break; default: Console.WriteLine("Your number {0} is not between 1 and 3.", myInt); break; } By placing case statements together, with no code in-between, you create a single case for multiple values. A case without any code will automatically fall through to the next case. The example above shows how the three cases for myInt equal to 1, 2, or 3, where case 1 and case 2 will fall through and execute code for case 3. A case statement can only be an exact match and you can't use logical conditions. If you need to use logical conditions, you can use an if/else if/else statement. Another way to control the flow of logic in a switch statement is by using the goto statement. You can either jump to another case statement, or jump out of the switch statement. The second switch statement in Listing 3-2 shows the use of the goto statement, as shown below: // switch with string type switch (myInput) { case "continue": goto begin; case "quit": Console.WriteLine("Bye."); break; default: Console.WriteLine("Your input {0} is incorrect.", myInput); goto decide; } Note: in the current example, "continue", is a case of the switch statement -- not the keyword. The goto statement causes program execution to jump to the label following the goto keyword. During execution, if the user types in "continue", the switch statement matches this input (a string type) with the case "continue": label and executes the "goto begin:" instruction. The program will then leave the switch statement and start executing the first program statement following the begin: label. This is effectively a loop, allowing you to execute the same code multiple times. The loop will end when the user types the string "quit". This will be evaluated with the case "quit": choice, which will print "Bye." to the console, break out of the switch statement and end the program. Warning: You should not create loops like this. It is *bad* programming style. The only reason it is here is because I wanted to show you the syntax of the goto statement. Instead, use one of the structured looping statements, described in Lesson 04: Control Statements - Loops. When neither the "continue" nor "quit" strings are entered, the "default:" case will be entered. It will print an error message to the console and then execute the goto decide: command. This will cause program execution to jump to the first statement following the decide: label, which will ask the user if they want to continue or quit. This is effectively another loop. Clearly, the goto statement is powerful and can, under controlled circumstances, be useful. However, I must caution you strongly on its use. The goto statement has great potential for misuse. You could possibly create a very difficult program to debug and maintain. Imagine the spaghetti code that could be created by random goto statements throughout a program. In the next lesson, I'll show you a better way to create loops in your program. Summary The if statement can be written in multiple ways to implement different branches of logic. The switch statement allows a choice among a set of bool, enum, integral, or string types. You use break, continue, goto, return, or throw statements to leave a case statement. Be sure to avoid the goto statement in your code unless you have an extremely good reason for using it. In addition to branching based on a condition, it is useful to be able to execute a block of statements multiple times. A goto statement is not proper or adequate for such logic. Therefore, I invite you to return for Lesson 4: Control Statements - Loops. This will be a continuation of the same topic.

The C# Station Tutorial by Joe Mayo created 8/27/00, updated 10/6/01, 3/12/03, 1/22/05, 2/21/08, 4/29/08, 8/16/08, 10/11/08, 1/12/09, 9/2/11 Lesson 2: Operators, Types, and Variables This lesson introduces C# operators, types, and variables. Its goal is to meet the following objectives: Understand what a variable is. Familiarization with C# built-in types. Get an introduction to C# operators. Learn how to use Arrays. Variables and Types "Variables" are simply storage locations for data. You can place data into them and retrieve their contents as part of a C# expression. The interpretation of the data in a variable is controlled through "Types". C# is a "Strongly Typed" language. Thus all operations on variables are performed with consideration of what the variable's "Type" is. There are rules that define what operations are legal in order to maintain the integrity of the data you put in a variable. The C# simple types consist of the Boolean type and three numeric types - Integrals, Floating Point, Decimal, and String. The term "Integrals", which is defined in the C# Programming Language Specification, refers to the classification of types that include sbyte, byte, short, ushort, int, uint, long, ulong, and char. More details are available in the Integral Types section later in this lesson. The term "Floating Point" refers to the float and double types, which are discussed, along with the decimal type, in more detail in the Floating Point and Decimal Types section later in this lesson. The string type represents a string of characters and is discussed in The String Type section, later in this lesson. The next section introduces the boolean type. The Boolean Type Boolean types are declared using the keyword, bool. They have two values: true or false. In other languages, such as C and C++, boolean conditions can be satisfied where 0 means false and anything else means true. However, in C# the only values that satisfy a boolean condition is true and false, which are official keywords. Listing 2-1 shows one of many ways that boolean types can be used in a program. Listing 2-1. Displaying Boolean Values: Boolean.cs using System; class Booleans { public static void Main() { bool content = true; bool noContent = false; Console.WriteLine("It is {0} that C# Station provides C# programming language content.", content); Console.WriteLine("The statement above is not {0}.", noContent); } } In Listing 2-1, the boolean values are written to the console as a part of a sentence. The only legal values for the bool type are either true or false, as shown by the assignment of true to content and false to noContent. When run, this program produces the following output: It is True that C# Station provides C# programming language content. The statement above is not False. Integral Types In C#, an integral is a category of types. For anyone confused because the word Integral sounds like a mathematical term, from the perspective of C# programming, these are actually defined as Integral types in the C# programming language specification. They are whole numbers, either signed or unsigned, and the char type. The char type is a Unicode character, as defined by the Unicode Standard. For more information, visit The Unicode Home Page. table 2-1 shows the integral types, their size, and range. Table 2-1. The Size and Range of C# Integral Types Type Size (in bits) Range sbyte 8 -128 to 127 byte 8 0 to 255 short 16 -32768 to 32767 ushort 16 0 to 65535 int 32 -2147483648 to 2147483647 uint 32 0 to 4294967295 long 64 -9223372036854775808 to 9223372036854775807 ulong 64 0 to 18446744073709551615 char 16 0 to 65535 Integral types are well suited for those operations involving whole number calculations. The char type is the exception, representing a single Unicode character. As you can see from the table above, you have a wide range of options to choose from, depending on your requirements. Floating Point and Decimal Types A C# floating point type is either a float or double. They are used any time you need to represent a real number, as defined by IEEE 754. For more information on IEEE 754, visit the IEEE Web Site. Decimal types should be used when representing financial or money values. table 2-2 shows the floating point and decimal types, their size, precision, and range. Table 2-2. The Floating Point and Decimal Types with Size, precision, and Range Type Size (in bits) precision Range float 32 7 digits 1.5 x 10-45 to 3.4 x 1038 double 64 15-16 digits 5.0 x 10-324 to 1.7 x 10308 decimal 128 28-29 decimal places 1.0 x 10-28 to 7.9 x 1028 Floating point types are used when you need to perform operations requiring fractional representations. However, for financial calculations, the decimal type is the best choice because you can avoid rounding errors. The string Type A string is a sequence of text characters. You typically create a string with a string literal, enclosed in quotes: "This is an example of a string." You've seen strings being used in Lesson 1, where we used the Console.WriteLine method to send output to the console. Some characters aren't printable, but you still need to use them in strings. Therefore, C# has a special syntax where characters can be escaped to represent non-printable characters. For example, it is common to use newlines in text, which is represented by the '\n' char. The backslash, '\', represents the escape. When preceded by the escape character, the 'n' is no longer interpreted as an alphabetical character, but now represents a newline. You may be now wondering how you could represent a backslash character in your code. We have to escape that too by typing two backslashes, as in '\\'. table 2-3 shows a list of common escape sequences. Table 2-3. C# Character Escape Sequences Escape Sequence Meaning \' Single Quote \" Double Quote \\ Backslash \0 Null, not the same as the C# null value \a Bell \b Backspace \f form Feed \n Newline \r Carriage Return \t Horizontal Tab \v Vertical Tab Another useful feature of C# strings is the verbatim literal, which is a string with a @ symbol prefix, as in @"Some string". Verbatim literals make escape sequences translate as normal characters to enhance readability. To appreciate the value of verbatim literals, consider a path statement such as "c:\\topdir\\subdir\\subdir\\myapp.exe". As you can see, the backslashes are escaped, causing the string to be less readable. You can improve the string with a verbatim literal, like this: @"c:\topdir\subdir\subdir\myapp.exe". That is fine, but now you have the problem where quoting text is not as easy. In that case, you would specify double double quotes. For example, the string "copy \"c:\\source file name with spaces.txt\" c:\\newfilename.txt" would be written as the verbatim literal @"copy ""c:\source file name with spaces.txt"" c:\newfilename.txt". C# Operators Results are computed by building expressions. These expressions are built by combining variables and operators together into statements. The following table describes the allowable operators, their precedence, and associativity. Table 2-4. Operators with their precedence and Associativity Category (by precedence) Operator(s) Associativity Primary x.y f(x) a[x] x++ x-- new typeof default checked unchecked delegate left Unary + - ! ~ ++x --x (T)x right Multiplicative * / % left Additive + - left Shift << >> left Relational < > <= >= is as left Equality == != right Logical AND & left Logical XOR ^ left Logical OR | left Conditional AND && left Conditional OR || left Null Coalescing ?? left Ternary ?: right Assignment = *= /= %= += -= <<= >>= &= ^= |= => right Left associativity means that operations are evaluated from left to right. Right associativity mean all operations occur from right to left, such as assignment operators where everything to the right is evaluated before the result is placed into the variable on the left. Most operators are either unary or binary. Unary operators form expressions on a single variable, but binary operators form expressions with two variables. Listing 2-2 demonstrates how unary operators are used. Listing 2-2. Unary Operators: Unary.cs using System; class Unary { public static void Main() { int unary = 0; int preIncrement; int preDecrement; int postIncrement; int postDecrement; int positive; int negative; sbyte bitNot; bool logNot; preIncrement = ++unary; Console.WriteLine("pre-Increment: {0}", preIncrement); preDecrement = --unary; Console.WriteLine("pre-Decrement: {0}", preDecrement); postDecrement = unary--; Console.WriteLine("Post-Decrement: {0}", postDecrement); postIncrement = unary++; Console.WriteLine("Post-Increment: {0}", postIncrement); Console.WriteLine("Final Value of Unary: {0}", unary); positive = -postIncrement; Console.WriteLine("Positive: {0}", positive); negative = +postIncrement; Console.WriteLine("Negative: {0}", negative); bitNot = 0; bitNot = (sbyte)(~bitNot); Console.WriteLine("Bitwise Not: {0}", bitNot); logNot = false; logNot = !logNot; Console.WriteLine("Logical Not: {0}", logNot); } } When evaluating expressions, post-increment (x++) and post-decrement (x--) operators return their current value and then apply the operators. However, when using pre-increment (++x) and pre-decrement (--x) operators, the operator is applied to the variable prior to returning the final value. In Listing 2-2, the unary variable is initialized to zero. When the pre-increment (++x) operator is used, unary is incremented to 1 and the value 1 is assigned to the preIncrement variable. The pre-decrement (--x) operator turns unary back to a 0 and then assigns the value to the preDecrement variable. When the post-decrement (x--) operator is used, the value of unary, 0, is placed into the postDecrement variable and then unary is decremented to -1. Next the post-increment (x++) operator moves the current value of unary, -1, to the postIncrement variable and then increments unary to 0. The variable bitNot is initialized to 0 and the bitwise not (~) operator is applied. The bitwise not (~) operator flips the bits in the variable. In this case, the binary representation of 0, "00000000", was transformed into -1, "11111111". While the (~) operator works by flipping bits, the logical negation operator (!) is a logical operator that works on bool values, changing true to false or false to true. In the case of the logNot variable in Listing 2-2, the value is initialized to false, and the next line applies the logical negation operator, (!), which returns true and reassigns the new value, true, to logNot. Essentially, it is toggling the value of the bool variable, logNot. The setting of positive is a little tricky. At the time that it is set, the postIncrement variable is equal to -1. Applying the minus (-) operator to a negative number results in a positive number, meaning that positive will equal 1, instead of -1. The minus operator (-), which is not the same as the pre-decrement operator (--), doesn't change the value of postInc - it just applies a sign negation. The plus operator (+) doesn't affect the value of a number, assigning negative with the same value as postIncrement, -1. Notice the expression (sbyte)(~bitNot). Any operation performed on types sbyte, byte, short, or ushort return int values. To assign the result into the bitNot variable we had to use a cast, (Type), operator, where Type is the type you wish to convert to (in this case - sbyte). The cast operator is shown as the Unary operator, (T)x, in table 2-4. Cast operators must be performed explicity when you go from a larger type to a smaller type because of the potential for lost data. Generally speaking, assigning a smaller type to a larger type is no problem, since the larger type has room to hold the entire value. Also be aware of the dangers of casting between signed and unsigned types. You want to be sure to preserve the integrity of your data. Many basic programming texts contain good descriptions of bit representations of variables and the dangers of explicit casting. Here's the output from the Listing 2-2: pre-Increment: 1 pre-Decrement 0 Post-Decrement: 0 Post-Increment: -1 Final Value of Unary: 0 Positive: 1 Negative: -1 Bitwise Not: -1 Logical Not: true In addition to unary operators, C# has binary operators that form expressions of two variables. Listing 2-3 shows how to use the binary operators. Listing 2-3. Binary Operators: Binary.cs using System; class Binary { public static void Main() { int x, y, result; float floatresult; x = 7; y = 5; result = x+y; Console.WriteLine("x+y: {0}", result); result = x-y; Console.WriteLine("x-y: {0}", result); result = x*y; Console.WriteLine("x*y: {0}", result); result = x/y; Console.WriteLine("x/y: {0}", result); floatresult = (float)x/(float)y; Console.WriteLine("x/y: {0}", floatresult); result = x%y; Console.WriteLine("x%y: {0}", result); result += x; Console.WriteLine("result+=x: {0}", result); } } And here's the output: x+y: 12 x-y: 2 x*y: 35 x/y: 1 x/y: 1.4 x%y: 2 result+=x: 9 Listing 2-3 shows several examples of binary operators. As you might expect, the results of addition (+), subtraction (-), multiplication (*), and division (/) produce the expected mathematical results. The floatresult variable is a floating point type. We explicitly cast the integer variables x and y to calculate a floating point value. There is also an example of the remainder(%) operator. It performs a division operation on two values and returns the remainder. The last statement shows another form of the assignment with operation (+=) operator. Any time you use the assignment with operation operator, it is the same as applying the binary operator to both the left hand and right hand sides of the operator and putting the results into the left hand side. The example could have been written as result = result + x; and returned the same value. The Array Type Another data type is the Array, which can be thought of as a container that has a list of storage locations for a specified type. When declaring an Array, specify the type, name, dimensions, and size. Listing 2-4. Array Operations: Array.cs using System; class Array { public static void Main() { int[] myInts = { 5, 10, 15 }; bool[][] myBools = new bool[2][]; myBools[0] = new bool[2]; myBools[1] = new bool[1]; double[,] myDoubles = new double[2, 2]; string[] myStrings = new string[3]; Console.WriteLine("myInts[0]: {0}, myInts[1]: {1}, myInts[2]: {2}", myInts[0], myInts[1], myInts[2]); myBools[0][0] = true; myBools[0][1] = false; myBools[1][0] = true; Console.WriteLine("myBools[0][0]: {0}, myBools[1][0]: {1}", myBools[0][0], myBools[1][0]); myDoubles[0, 0] = 3.147; myDoubles[0, 1] = 7.157; myDoubles[1, 1] = 2.117; myDoubles[1, 0] = 56.00138917; Console.WriteLine("myDoubles[0, 0]: {0}, myDoubles[1, 0]: {1}", myDoubles[0, 0], myDoubles[1, 0]); myStrings[0] = "Joe"; myStrings[1] = "Matt"; myStrings[2] = "Robert"; Console.WriteLine("myStrings[0]: {0}, myStrings[1]: {1}, myStrings[2]: {2}", myStrings[0], myStrings[1], myStrings[2]); } } And here's the output: myInts[0]: 5, myInts[1]: 10, myInts[2]: 15 myBools[0][0]: true, myBools[1][0]: true myDoubles[0, 0]: 3.147, myDoubles[1, 0]: 56.00138917 myStrings[0]: Joe, myStrings[1]: Matt, myStrings[2]: Robert Listing 2-4 shows different implementations of Arrays. The first example is the myInts Array, which is a single-dimension array. It is initialized at declaration time with explicit values. Next is a jagged array, myBools. It is essentially an array of arrays. We needed to use the new operator to instantiate the size of the primary array and then use the new operator again for each sub-array. The third example is a two dimensional array, myDoubles. Arrays can be multi-dimensional, with each dimension separated by a comma. It must also be instantiated with the new operator. One of the differences between jagged arrays, myBools[][], and multi-dimension arrays, myDoubles[,], is that a multi-dimension array will allocate memory for every element of each dimension, whereas a jagged array will only allocate memory for the size of each array in each dimension that you define. Most of the time, you'll be using multi-dimension arrays, if you need multiple dimensions, and will only use jagged arrays in very special circumstances when you are able to save significant memory by explicitly specifying the sizes of the arrays in each dimension. Finally, we have the single-dimensional array of string types, myStrings. In each case, you can see that array elements are accessed by identifying the integer index for the item you wish to refer to. Arrays sizes can be any int type value. Their indexes begin at 0. Summary A variable is an identifier with a type that holds a value of that type. Simple types include the integrals, floating points, decimal, and bool. C# has several mathematical and logical operators that participate in forming expressions. C# also offers the single dimension, multi-dimension and jagged array types. In this lesson you learned how to write simple statements and code a program that works linearly from start to finish. However, this is not as useful as it can be because you need to be able to make decisions and execute different blocks of code depending on different conditions. I invite you to return for Lesson 3: Control Statements - Selection, where you can learn how to branch your logic for more powerful decision making.

The C# Station Tutorial by Joe Mayo created 8/20/00, updated 9/24/01, 3/6/03, 8/16/03, 1/16/05, 4/30/07, 2/21/08, 3/12/08, 4/29/08, 7/6/08, 8/16/08, 1/12/09, 9/2/11 Lesson 1: Getting Started with C# This lesson will get you started with C# by introducing a few very simple programs. Here are the objectives of this lesson: Understand the basic structure of a C# program. Obtain a basic familiarization of what a "Namespace" is. Obtain a basic understanding of what a Class is. Learn what a Main method does. Learn how to obtain command-line input. Learn about console input/output (I/O). A Simple C# Program There are basic elements that all C# executable programs have and that's what we'll concentrate on for this first lesson, starting off with a simple C# program. After reviewing the code in Listing 1-1, I'll explain the basic concepts that will follow for all C# programs we will write throughout this tutorial. Please see Listing 1-1 to view this first program. Warning: C# is case-sensitive. Listing 1-1. A Simple Welcome Program: Welcome.cs // Namespace Declaration using System; // Program start class class WelcomeCSS { // Main begins program execution. static void Main() { // Write to console Console.WriteLine("Welcome to the C# Station Tutorial!"); } } The program in Listing 1-1 has 4 primary elements, a namespace declaration, a class, a Main method, and a program statement. It can be compiled with the following command line: csc.exe Welcome.cs This produces a file named Welcome.exe, which can then be executed. Other programs can be compiled similarly by substituting their file name instead of Welcome.cs. For more help about command line options, type "csc -help" on the command line. The file name and the class name can be totally different. Note for VS.NET Users: The screen will run and close quickly when launching this program from Visual Studio .NET. To prevent this, add the following code as the last line in the Main method: // keep screen from going away // when run from VS.NET Console.ReadLine(); Note: The command-line is a window that allows you to run commands and programs by typing the text in manually. It is often refered to as the DOS prompt, which was the operating system people used years ago, before Windows. The .NET Framework SDK, which is free, uses mostly command line tools. Therefore, I wrote this tutorial so that anyone would be able to use it. Do a search through Windows Explorer for "csc.exe", which is the C# compiler. When you know its location, add that location to your Windows path. Then open the command window by going to the Windows Start menu, selecting Run, and typing cmd.exe. This blog post might be helpful: How to set the path in Windows 7. The first thing you should be aware of is that C# is case-sensitive. The word "Main" is not the same as its lower case spelling, "main". They are different identifiers. If you are coming from a language that is not case sensitive, this will trip you up several times until you become accustomed to it. The namespace declaration, using System;, indicates that you are referencing the System namespace. Namespaces contain groups of code that can be called upon by C# programs. With the using System; declaration, you are telling your program that it can reference the code in the System namespace without pre-pending the word System to every reference. I'll discuss this in more detail in Lesson 06: Namespaces, which is dedicated specifically to namespaces. The class declaration, class WelcomeCSS, contains the data and method definitions that your program uses to execute. A class is one of a few different types of elements your program can use to describe objects, such as structs, interfaces , delegates, and enums, which will be discussed in more detail in Lesson 12: Structs, Lesson 13: Interfaces, Lesson 14: Delegates, and Lesson 17: Enums, respectively. This particular class has no data, but it does have one method. This method defines the behavior of this class (or what it is capable of doing). I'll discuss classes more in Lesson 07: Introduction to Classes. We'll be covering a lot of information about classes throughout this tutorial. The one method within the WelcomeCSS class tells what this class will do when executed. The method name, Main, is reserved for the starting point of a program. Main is often called the "entry point" and if you ever receive a compiler error message saying that it can't find the entry point, it means that you tried to compile an executable program without a Main method. A static modifier precedes the word Main, meaning that this method works in this specific class only, rather than an instance of the class. This is necessary, because when a program begins, no object instances exist. I'll tell you more about classes, objects, and instances in Lesson 07: Introduction to Classes. Every method must have a return type. In this case it is void, which means that Main does not return a value. Every method also has a parameter list following its name with zero or more parameters between parenthesis. For simplicity, we did not add parameters to Main. Later in this lesson you'll see what type of parameter the Main method can have. You'll learn more about methods in Lesson 05: Methods. The Main method specifies its behavior with the Console.WriteLine(...) statement. Console is a class in the System namespace. WriteLine(...) is a method in the Console class. We use the ".", dot, operator to separate subordinate program elements. Note that we could also write this statement as System.Console.WriteLine(...). This follows the pattern "namespace.class.method" as a fully qualified statement. Had we left out the using System declaration at the top of the program, it would have been mandatory for us to use the fully qualified form System.Console.WriteLine(...). This statement is what causes the string, "Welcome to the C# Station Tutorial!" to print on the console screen. Observe that comments are marked with "//". These are single line comments, meaning that they are valid until the end-of-line. If you wish to span multiple lines with a comment, begin with "/*" and end with "*/". Everything in between is part of the comment. Comments are ignored when your program compiles. They are there to document what your program does in plain English (or the native language you speak with every day). All statements end with a ";", semi-colon. Classes and methods begin with "{", left curly brace, and end with a "}", right curly brace. Any statements within and including "{" and "}" define a block. Blocks define scope (or lifetime and visibility) of program elements. Accepting Command-Line Input In the previous example, you simply ran the program and it produced output. However, many programs are written to accept command-line input. This makes it easier to write automated scripts that can invoke your program and pass information to it. If you look at many of the programs, including Windows OS utilities, that you use everyday; most of them have some type of command-line interface. For example, if you type Notepad.exe MyFile.txt (assuming the file exists), then the Notepad program will open your MyFile.txt file so you can begin editing it. You can make your programs accept command-line input also, as shown in Listing 1-2, which shows a program that accepts a name from the command line and writes it to the console. Danger! Regardless of the fact that I documented the proper use of command-line arguments before and after Listing 1-2, some people still send me email to complain that they get an error or tell me there's a bug in my program. In fact, I get more email on this one subject than any other in the whole tutorial. Please read the instructions to include the command-line argument. Note: When running the NamedWelcome.exe application in Listing 1-2, you must supply a command-line argument. For example, type the name of the program, followed by your name: NamedWelcome YourName. This is the purpose of Listing 1-2 - to show you how to handle command-line input. Therefore, you must provide an argument on the command-line for the program to work. If you are running Visual Studio, right-click on the project in Solution Explorer, select Properties, click the Debug tab, locate Start Options, and type YourName into Command line arguments. If you forget to to enter YourName on the command-line or enter it into the project properties, as I just explained, you will receive an exception that says "Index was outside the bounds of the array." To keep the program simple and concentrate only on the subject of handling command-line input, I didn't add exception handling. Besides, I haven't taught you how to add exception handling to your program yet - but I will. In Lesson 15: Introduction to Exception Handling, you'll learn more about exceptions and how to handle them properly. Listing 1-2. Getting Command-Line Input: NamedWelcome.cs // Namespace Declaration using System; // Program start class class NamedWelcome { // Main begins program execution. static void Main(string[] args) { // Write to console Console.WriteLine("Hello, {0}!", args[0]); Console.WriteLine("Welcome to the C# Station Tutorial!"); } } Tip: Remember to add your name to the command-line, i.e. "NamedWelcome Joe". If you don't, your program will crash. I'll show you in Lesson 15: Introduction to Exception Handling how to detect and avoid such error conditions. If you are using an IDE, like Visual Studio, see your IDE's help documentation on how to set the command-line option via project properties. i.e. in Visual Studio 2010, double-click the Properties folder in your solution project, click the Debug tab, and add your name to Command Line Arguments. The actual step can/will differ between IDE's and versions, so please consult your IDE documentation for more information. In Listing 1-2, you'll notice an entry in the Main method's parameter list. The parameter name is args, which you'll use to refer to the parameter later in your program. The string[] expression defines the type of parameter that args is. The string type holds characters. These characters could form a single word, or multiple words. The "[]", square brackets denote an Array, which is like a list. Therefore, the type of the args parameter, is a list of words from the command-line. Anytime you add string[] args to the parameter list of the Main method, the C# compiler emits code that parses command-line arguments and loads the command-line arguments into args. By reading args, you have access to all arguments, minus the application name, that were typed on the command-line. You'll also notice an additional Console.WriteLine(...) statement within the Main method. The argument list within this statement is different than before. It has a formatted string with a "{0}" parameter embedded in it. The first parameter in a formatted string begins at number 0, the second is 1, and so on. The "{0}" parameter means that the next argument following the end quote will determine what goes in that position. Hold that thought, and now we'll look at the next argument following the end quote. The args[0] argument refers to the first string in the args array. The first element of an Array is number 0, the second is number 1, and so on. For example, if I typed NamedWelcome Joe on the command-line, the value of args[0] would be "Joe". This is a little tricky because you know that you typed NamedWelcome.exe on the command-line, but C# doesn't include the executable application name in the args list - only the first parameter after the executable application. Returning to the embedded "{0}" parameter in the formatted string: Since args[0] is the first argument, after the formatted string, of the Console.WriteLine() statement, its value will be placed into the first embedded parameter of the formatted string. When this command is executed, the value of args[0], which is "Joe" will replace "{0}" in the formatted string. Upon execution of the command-line with "NamedWelcome Joe", the output will be as follows: Hello, Joe! Welcome to the C# Station Tutorial! Interacting via the Command-Line Besides command-line input, another way to provide input to a program is via the Console. Typically, it works like this: You prompt the user for some input, they type something in and press the Enter key, and you read their input and take some action. Listing 1-3 shows how to obtain interactive input from the user. Listing 1-3. Getting Interactive Input: InteractiveWelcome.cs // Namespace Declaration using System; // Program start class class InteractiveWelcome { // Main begins program execution. public static void Main() { // Write to console/get input Console.Write("What is your name?: "); Console.Write("Hello, {0}! ", Console.ReadLine()); Console.WriteLine("Welcome to the C# Station Tutorial!"); } } In Listing 1-3, the Main method doesn't have any parameters -- mostly because it isn't necessary this time. Notice also that I prefixed the Main method declaration with the public keyword. The public keyword means that any class outside of this one can access that class member. For Main, it doesn't matter because your code would never call Main, but as you go through this tutorial, you'll see how you can create classes with members that must be public so they can be used. The default access is private, which means that only members inside of the same class can access it. Keywords such as public and private are referred to as access modifiers. Lesson 19: Encapsulation discusses access modifiers in more depth. There are three statements inside of Main and the first two are different from the third. They are Console.Write(...) instead of Console.WriteLine(...). The difference is that the Console.Write(...) statement writes to the console and stops on the same line, but the Console.WriteLine(...) goes to the next line after writing to the console. The first statement simply writes "What is your name?: " to the console. The second statement doesn't write anything until its arguments are properly evaluated. The first argument after the formatted string is Console.ReadLine(). This causes the program to wait for user input at the console. After the user types input, their name in this case, they must press the Enter key. The return value from this method replaces the "{0}" parameter of the formatted string and is written to the console. This line could have also been written like this: string name = Console.ReadLine(); Console.Write("Hello, {0}! ", name); The last statement writes to the console as described earlier. Upon execution of the command-line with "InteractiveWelcome", the output will be as follows: >What is your Name? [Enter Key] >Hello, ! Welcome to the C# Station Tutorial! Summary Now you know the basic structure of a C# program. using statements let you reference a namespace and allow code to have shorter and more readable notation. The Main method is the entry point to start a C# program. You can capture command-line input when an application is run by reading items from a string[] (string array) parameter to your Main method. Interactive I/O can be performed with the ReadLine, Write and WriteLine methods of the Console class.

Welcome Welcome to C# Station! This is a community site for people interested in applying .NET using the C# programming language. We've been around since July 4th 2000 and have continued to grow over the years. Items of interest include Articles, Books, Links, Documentation, and Tutorials. More... Who Operates this Site? This site is owned and operated by Joe Mayo. Besides articles and tutorials on this site, Joe is a published author. His latest book, LINQ Programming is available now. Joe has a blog too. You can also follow Joe on Twitter. Also, check out Joe's Xamarin Evolve 2014 presentation, Applying C# Async in Mobile. Source Code If you would like to see an entire application written in C#, visit LINQ to Twitter, an open source LINQ Provider for the Twitter Micro-Blogging Service. What is C#? C# (pronounced "see sharp" or "C Sharp") is one of many .NET programming languages. It is object-oriented and allows you to build reusable components for a wide variety of application types Microsoft introduced C# on June 26th, 2000 and it became a v1.0 product on Feb 13th 2002. C# is an evolution of the C and C++ family of languages. However, it borrows features from other programming languages, such as Delphi and Java. If you look at the most basic syntax of both C# and Java, the code looks very similar, but then again, the code looks a lot like C++ too, which is intentional. Developers often ask questions about why C# supports certain features or works in a certain way. The answer is often rooted in it's C++ heritage. Recent language features, such as Language Integrated Query (LINQ) and Asynchronous Programming (Async) are not necessarily unique to C#, but do add to it's uniqueness. How Does a C# Application Run? An important point is that C# is a "managed" language, meaning that it requires the .NET Common Language Runtime (CLR) to execute. Essentially, as an application that is written in C# executes, the CLR is managing memory, performing garbage collection, handling exceptions, and providing many more services that you, as a developer, don't have to write code for. The C# compiler produces Intermediate Language (IL) , rather than machine language, and the CLR understands IL. When the CLR sees the IL, it Just-In-Time (JIT) compiles it, method by method, into compiled machine code in memory and executes it. As mentiond previously, the CLR manages the code as it executes. Because C# requires the CLR, you must have the CLR installed on your system. All new Windows operating systems ship with a version of the CLR and it is available via Windows Update for older systems. The CLR is part of the .NET, so if you see updates for the .NET Framework Runtime, it contains the CLR and .NET Framework Class Library (FCL). It follows that if you copy your C# application to another machine, then that machine must have the CLR installed too. Does C# Have a Runtime Library? Instead of a runtime library (such as APIs for file I/O, string handling, etc.) being dedicated to a single language, .NET ships with a .NET Framework Class Library (FCL), which includes literally tens of thousands of reusable objects. Since all .NET languages target the CLR with the same IL, all languages can use the FCL. This shortens the learning curve for any developer moving from one .NET language to another, but also means that Microsoft is able to add many more features because there is only one FCL, rather than a separate implementation for common features in every programming language. Similarly, 3rd party software vendors can write managed code that any .NET developer, regardless of language, can use. In addition to all of the services you would expect of a runtime library, such as collections, file I/O, networking, etc., the FCL includes the APIs for all of the other .NET technologies, such as for desktop and Web development. What can I do with C#? C# is only a programming language. However, because C# targets the CLR and has access to the entire FCL, there's a lot you can do. To get an idea of the possibilities, open the FCL and look at the available technologies. You can write desktop applications with Windows Presentation Foundation (WPF) and Console applications. For the Web, you can write ASP.NET applications. When you need to access data, there is The ADO.NET Entity Framework and LINQ. Some of Microsoft's newest technologies include Windows Store and Windows Phone. You can also write scalable cloud apps with Windows Azure. Of course, these are only a few of the technologies available and as a general purpose programming language, you can do a lot more than this with C#. How Do I Get Started? By visiting this page and reading this far, you've already begun. You can continue your journey with the Free C# Tutorial right here at C# Station. The C# Tutorial was created to help beginning developers and other professionals who need a quick on-ramp to the language.

Top 10 Internet tips and tricks

Top 10 Internet tips and tricks You don't need the http:// portion of a web page When entering an Internet address you do not need to type http:// or even www. in the address. For example, if you wanted to visit Computer Hope you could just type computerhope.com and press enter. To make things even quicker, if you are visiting a .com address you can type computerhope and then press Ctrl + Enter to type out the full http://www.computerhope.com address. Quickly move between the fields of a web page If you are filling out an online form, e-mail, or other text field you can quickly move between each of the fields by pressing the Tab key or Shift + Tab to move back a field. For example, in the example form below you can click in the "First Name" field type anything and press tab to switch to the next field. Example Form First Name: Last Name: E-mail: Tip: This tip also applies to the buttons, if you press tab and the web developer has designed correctly the button should be selected and allows you to press the space bar or enter to push the button. Tip: With a drop-down box that lists dozens of options you can press the first letter to scroll down to that letter. For example, click the drop down box below and then press "u" to quickly scroll to Utah. Know your Internet browser shortcuts Internet browsersThere are dozens of different shortcut keys that can be used with Internet browsers. Below are a few of our top suggested Internet browser shortcuts. Press Alt + D to move the cursor into the address bar. Hold down the Ctrl key and press the + or - to increase and decrease the size of text. Ctrl + 0 will reset the text. Press the backspace key or press Alt key + left arrow to go back a page. Press F5 to refresh or reload a web page. Press F11 to make the Internet browser screen full screen. Press F11 again to return to the normal view. Press Ctrl + B to open your Internet bookmarks. Press Ctrl + F to open the find box to search for text within the web page you are reading. Related pages Full listing of Internet Explorer shortcut keys. Full listing of Mozilla Firefox shortcut keys. Protect yourself and avoid bad websites How can I protect myself while online? Avoid Internet phishing. Protecting children from harmful material and people on the Internet. Take advantage of tabbed browsing Take full advantage of tabbed browsing on all Internet browsers. While reading any web page if you come across a link that interests you open the link in a new tab so it doesn not interrupt your reading. A new tab can be opened by holding down the Ctrl key and clicking the link or if you have a mouse with a wheel press down on the wheel to use it as a middle mouse button to open the link in a new tab. Use Internet search engines to their full potential Get the most out of every search result. If you are not finding what you want try surrounding the text in quotes. For example, searching for 'computer help' without quotes returns results with "computer" and "help" anywhere on the page. However, if you search for "computer help" with the quotes it only return pages with "computer" and "help" next to each other. Tip: In every search box you can press enter instead of using the mouse to click the Search button. Top 10 unknown Google tricks Try alternative browsers Most computer users use the default browser that comes included with the computer, with Microsoft Windows this is Internet Explorer. There are many great alternative browsers that are all free to download and use and may have features your current browser does not include. Below are a few of our favorites, try one or try them all. Google Chrome Mozilla Firefox Opera Install plugins and add-ons All of the above alternative browsers also have a large community of volunteers who develop add-ons and plugins that can be added into the browser. Each of these browsers has hundreds of thousands of these add-ons that can do such things like the current weather in your browser window, changing its color, and adding additional functionality. Top 10 Firefox add-ons Make sure your browser and its plugins are up-to-date An Internet browser can have many plugins that give it additional functionality. For example, Adobe Flash is a great way to bring movies and other animated content to the Internet. Keeping these plugins up-to-date is vital for your computer stability and also security. Using the below tool you can quickly verify if your plugins are up-to-date and get links to where to download the latest updates. Computer Hope system information tool Use online services There are hundreds of free online services that can help make using your computer easier, more productive, and more enjoyable. See our top 10 online services for a listing of our favorites.

How do I download or save a YouTube video to my computer?

How do I download or save a YouTube video to my computer? YouTubeYouTube has been designed to only allow users to watch and view videos on their website. Many users want to save their favorite videos to their computer so they can watch them without being connected to the Internet or so they can watch them on other devices. Below are the steps required for downloading and watching YouTube videos on your computer for free. Note: These steps are for saving a YouTube video and not saving only the audio of a YouTube video to an MP3 file. How to watch a video or movie on a DVD disc is also not covered on this page. Saving YouTube video as a video file on your computer Today, there are many websites that allow you to enter the URL of the video you want to save to your computer and get a link to download the file. Below is a simple three-step process to download any YouTube video. Note: If you are at a school or job that is blocking YouTube, these steps may not work. 1. First, go to the YouTube page containing the video you want to save. When you've found the page, press Ctrl + L on your keyboard to highlight the text in the address bar, and then Ctrl + C to copy the Internet address. 2. Once this address has been copied, paste that URL into the text field below by clicking inside the box and pressing Ctrl + V on your keyboard. Then, click the Download Video button. 3. If done properly, a new window will appear displaying a preview of the video, (as shown below) along with the Download links. For most users, we suggest downloading the MP4 format. Other available formats may include FLV, 3GP, and WebM. Once you have selected your format, click the appropriate download link. YouTube download window After the file has been downloaded, it will be available in your downloads folder. What about a private video? You cannot download private videos because the YouTube download service will not have the necessary rights to access the video. I still can't download a video If after following the above steps, you do not get a preview like our example, make sure that the link you are using works by opening the page in a new window. Once verified as working, try the above steps again. If the steps continue to not work, try refreshing this page by pressing the F5 key on your keyboard and following the above steps again. If that still does not work, try one of the other YouTube download sites below. It is only saving as audio and not video Make sure you are choosing the "MP4 360p" or "MP4 480p" option from the download link. If you choose "Audio MP4 128", it only downloads the audio and not the video. If you did choose the right download link to download the file, it is very likely that the player you are using does not have the necessary codec for video files. Download the free VLC player for your computer and try to play the video file from within VLC and not the player you are currently using. YouTube bookmarklet If you plan on downloading several videos, use the Computer Hope YouTube bookmarklet. See our bookmarklet page for more information about bookmarklets. Other YouTube download sites In addition to using the above box to convert your videos, there are also other websites and services that allow you to download YouTube videos. Below are just a few of our favorites. Caution: These services can be used to save any flash videos online and can be used to save adult-related videos, which means when viewing these pages, you may be subjected to adult-related content. http://www.savefrom.net/ http://www.savevid.com/ http://keepvid.com/ Watching a FLV video on your computer If you saved the file as a .flv file, you need a player that supports .flv files. Below are a few suggestions. VLC media player http://www.videolan.org/ Windows Media Player Microsoft Windows users also have the ability of playing FLV files in Windows Media player with the right codec. Downloading and installing the CCCP codec installs the necessary codec to play FLV files, as well as other codecs you'll likely need in the future.