Introduction to C
Introduction to C
Introduction to Programming Projects
Introduction to Microsoft Visual Studio
A computer application is a series of instructions that ask the computer to do somehing. To create those instructions, you can use a computer language. One of the computer languages you can use to create a computer application is called C. Normally, you can write the instructions using a text editor and use some gymnastics to pass those instructions to the computer. To provide a better option, Microsoft created and makes available Microsoft Visual Studio, which you can freely download from one of the Microsoft websites (such as asp.net) and install it in your computer.
Starting a Project
After installing Microsoft Visual Studio, you can easily create a project using simple wizards.
Practical Learning: Starting a Project
Introduction to Source Files
C is a language that allows you to give instructions to a computer to perform one or a series of operations. To give those instructions, you write some text, referred to as code, in a text-based document. The C language supports various types of files. The primary type of file is the one in which you write direct instructions to the computer. This type of file is called a source file. It is also called a translation unit.
A source file is a text-based document. You must create the document and save it with the extension .c. If you are using Microsoft Visual Studio to create your project, to get a source file, in the Solution Explorer, right-click the Source Files folder -> Add -> New Item... Accept the suggested name or change it, but you must (explicitly) specify the file extension as .c. Then click Add.
Practical Learning: Creating a Source File
Comments
A comment is a section of code that the compiler will not consider when building your code. In other words, the compiler will skip the comment section. To create a comment, write /**/. Between the asterisks, write anything you want. Here is an example:
/* This series of lessons introduces computer programming using the C language. */
In the same way, you can create the comment on many lines as long as you start the section with /* and end it with */. Here is an example:
/* Source File: Exercise.c This source fill introduces the C language and its primary functionalities. The lessons follow a step-by-step detailed approach. */
A Compiler
A compiler is a computer application that gets your English-based human instructions and translates them in instructions that the computer can understand. A compiler is actually made of various internal programs that do different things.
There are many C compilers in the industry. If you are using Microsoft Visual Studio to create your applications, the compiler you are using is named Microsoft C.
A Directive
A directive is a piece of code that asks the compiler to take some specific action. There are many types of directives you will create in your code. Normally, all compilers use directives. We will what directives are available, when to use them, and why.
A Pragma
A pragma is a short line of code that informs the compiler about something or some things in the code of the document so the compiler is supposed to behave in a certain way. Pragmas are not universal. This means that some compilers use them and some others may not. Even among the compilers that use pragmas, they don't use them the same way or they don't give the same instructions. In these lessons, we will create all our applications using Microsoft Visual Studio. Therefore, we will use and apply only pragmas used by the Microsoft C compiler.
Header Files
Introduction
As mentioned already, the C language supports various types of files. Besides the source files, another type of document is called a header file. It is a text-based file that uses the extension .h. You can create such a file in any text editor, save it with the .h extension, and import it in your project.
If you are using Microsoft Visual Studio to create your project, to get a header file, in the Solution Explorer, right-click the Header Files folder -> Add -> New Item... In the middle list of the New Item dialog box, select Header File (.h). Accept the suggested name or change it. Then click Add.
In your header file, you can write just about any type of code. By tradition, a header file is used to make declarations, that is, to define the names of things you will use in your code. Therefore, after creating a header file and writing code in its document, if you want to use that code in your source file, you must reference the header file in your source file. To do this, you use a directive named #include.
There are two categories of header files you will use. The first category are header files that ship with the package you are using to create your projects. To refer to one of those header file, use the following formula:
#include <file-name.h>
If you want to refer to a header file you yourself had created, use the following formula:
#include "file-name.h"
After doing this, when your project is built, a copy of the header file would be virtually (not physically) added to the .cpp source file so that the source file will have available whatever is available in the header file.
The primary header file you will use in your code is named stdio.h. You should include it in your primary source file.
Practical Learning: Introducing Header Files
#include <stdio.h>
#include <stdio.h>
void main()
{
printf("Welcome");
}
In the above code, we have just added four lines of code that contain some things we haven't studied yet. At this time, there is no need to understand what those lines are. In later sections and lessons, we will know what each of those lines contain and why. |
To display something on the computer screen, write and include that thing in place of Welcome.
Introduction to Values and Storage
Introduction to Electronic Devices
A computer is an electronic device that is used to solve one specific problem or to perform an assignment. For example, a fitness machine allows a person to get in shape. A digital camera is used to take pictures. A cell phone is used to make phone calls. An ultrasound machine is a health care machine used to produce images from inside a human body. A music synthesizer can be used to create music:
|
The values used in an electronic device can come (internally) from various sources (car, projector, etc). A computer can also get its values from a combination of sources:
To manage these different connections, a computer uses a motherboard. Many parts are connected to this board:
The values a computer receives must be stored somewhere, called memory (like human memory). The memory area where the computer temporarily stores some values is called random access memory or RAM:
Let's illustrate memory as a small cake pan made of boxes or holes that can contain something:
We must mention, and keep in mind, that memory is larger than that and is made of millions of these hole-like objects.
As a programmer, your most regular job will consist of asking the compiler to temporarily store one or more values in the RAM. Other programs (and utilities) also occupy the RAM.
To be able to manage the frequent requests of memory of your application, when you start a program, the compiler reserves a certain area of memory:
Because many programs use the RAM, if/when you want to store a value in it, you must provide some pieces of information. You must indicate the amount or memory you need and you must create a name that would be used to refer to that area of memory. The combination of these two pieces of information is called a variable.
Introduction
The language the computer understands uses a combination of 1s and 0s. This means that the assembler must bring your C instructions to 1s and 0s. The combinations or sequences of 1s and 0s indicate what needs to be done.
Introduction to the Decimal System
We are familiar with the system that uses 10 digits as 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. A combination of these 10 digits can produce any number we want. Because this system uses 10 digits. It is named the decimal system.
Introduction to the Binary System
As mentioned already, the language of the computer is made of combinations of two values: 1 and 0. This is called the binary system (because it is based on two values only). Examples of numbers in the binary system, or binary numbers, are 1, 10, 1001, or 1010110111. When you submit a value to a computer, the value must be changed into a compbination of 1s and 0s.
Introduction to the Hexadecimal System
You can imagine how hard it would be to represent a large number. One alternative uses the 10 digits of the decimal system and uses the first 6 letters of the English alphabets: A, B, C, E, D, and F or a, b, c, d, e, and f. This means that this system uses a combination of 16 characters to create any number. For this reason, it is called the hexadecimal system. To differenciate a hexadecimal number from a word, the number must start with 0x. Examples are 0x2, or 0xED8, or 0x962AAED3.
A Bit
We mentioned that, to store a value in the computer memory, you must indicate how much memory you will need and you must give it a name. The amount of memory you need is referred to as a data type. As you can imagine, different values require different amounts of memory. We also mentioned that the computer considers a value as a combination of 1s and 0s. The area of memory that holds a single piece of 1 or 0 is called a bit.
Consider a bit like a small object (like a cup of a cup cake) that can be full or can be empty:
When it is empty, a bit holds a value or 0. When it is full, it holds a value of 1:
Different combinations of empty (0) and full (1) objects produce the necessary values.
A Nibble
Although there are cases where you can use or access a bit, you cannot actually store a value in it. That is, you cannot ask the compiler to store the value 1 in a certain bit. This is because even the simplest value needs more than one bit to store itself. Still, the minimum combination of bits you can be concerned with is four. Sometimes, such as in fthe Assembly language, a combination of four bits is called a nibble.
By creating different combinations of empty (0) and full (1) objects grouped in four, you can get 16 combinations:
In a combination of four bits, the bits are counted as 0, 1, 2, and 3. The bit on the most right side is Bit 0 and it is called the low order bit (or LOBIT):
The last bit, the bit on the most left side, is Bit 3 and it is called the high order bit (or HIBIT).
If you represent the four-combination bits in binary formats, you get 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111, which produces 16 combinations. In the decimal format, these combinations produce 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, and 15. In hexadecimal format, these combinations produce 0x0 (0x0000), 0x1 (or 0x0001), 0x2 (or 0x0002), 0x3 (or 0x0003), 0x4 (or 0x0004), 0x5 (0x0005), 0x6 (0x0006), 0x7 (or 0x0007), 0x8 (or 0x0008), 0x9 (or 0x0009), 0xA (or 0xa), 0xB (or 0xb), 0xC (or 0xc), 0xD (or 0xd), 0xE (or 0xe), and 0xF (or 0xF).
As a result, we get a table as follows:
Decimal | Binary | Hexadecimal |
0 | 0000 | 0x0 |
1 | 0001 | 0x1 |
2 | 0010 | 0x2 |
3 | 0011 | 0x3 |
4 | 0100 | 0x4 |
5 | 0101 | 0x5 |
6 | 0110 | 0x6 |
7 | 0111 | 0x7 |
8 | 1000 | 0x8 |
9 | 1001 | 0x9 |
10 | 1010 | 0xA |
11 | 1011 | 0xB |
12 | 1100 | 0xC |
13 | 1101 | 0xD |
14 | 1110 | 0xE |
15 | 1111 | 0xF |
Table of Numeric Conversions
The minimum and maximum values in a combination of four bits are:
Decimal | Hexadecimal | Binary | |
Minimum | 0 | 0x0 | 0000 |
Maximum | 15 | 0xf | 1111 |
You will never be concerned with combinations of four bits because you cannot store anything in it (these combinations are too small). We presented them here for two reasons. You should be aware of such a thing as a combination of four bits so you will know where the number 16 comes from when you see it mentioned in different places.
Introduction to Variables
Introduction to Definitions
The instructions of an application use regular words that a human being can read to humanly understand what is going on. Each of the words used must be clearly defined so it can be recognized by a program named compiler. A definition consists of naming something that will be used in your code.
Names
You will create a lot of names in your code. There are rules and suggestions you must use. A name can:
Additionally
When specifying the names of things in your code, don't use the following words. They are called keywords or reserved words and they are used by the language itself. These keywords are:
auto | break | case | char | double | else | long |
switch | enum | register | typedef | int | extern | |
return | union | const | float | short | unsigned | continue |
for | signed | void | default | goto | sizeof | volatile |
do | if | static | while | wchar_t | ||
struct | ||||||
There are other names that are not strictly considered keywords but avoid them:
_asm | dllimport | __int8 | naked | __based | __except |
__int16 | __stdcall | __cdecl | __fastcall | __int32 | thread |
__declspec | __finally | __int64 | __try | dllexport | __inline |
__leave |
Introduction to Declarations
A variable is an area you want to use in the computer memory to store a value. The amount of memory you want to use depends on the type of value you want to use. A data type is a word or a combination of words that indicates the amount of memory you need to store the value of the variable.
Before storing a value in the computer a memory, you must indicate your intention. This indication is referred to as declaring a variable. The primary formula to declare a variable is:
data-type variable-name
Start with a data type, a space, a name for the variable, and end the statement with a semicolon. Remember that the name you use is also referred to as a definition. In fact, before using a name in your code, you must first declare it.
When declaring a variable, if its name is not particularly important, you can use a letter of the alphabet as the name of the variable. This would be done as follows:
data-type i;
As an alternative, you can put the name of the variable in parentheses. Here is an example:
data-type (i);
Initializing a Variable
When you have declared a variable, if you build the project, the compiler reserves a memory area for that variable and stores garbage in that particular memory area. It is a good idea to store an actual and appropriate value in that memory. To do this, when declaring a variable, follow its name with the = sign and a value. The value must be of the type of data. This would be done as follows:
data-type i = value;
To actually declare a variable, you have two options.
data-type variable-name;In this case, you may or may not initialize the variable
auto variable-name = initial-value;
Displaying the Value of a Variable
One of the most important characteristics of an application is to display values on the computer screen. The basic formula to do this is:
printf(". . .%special-character . . . ", variable-name);
Therefore, start witt printf followed by parentheses. There is no good reason to have space between print and the parentheses but you can put space if you want. This means that printf() is valid, so is printf (), and so is printf (). In the parentheses, create some double-quotes (we will find out what the double-quotes are and why; just be patient).
You can write the starting double-quote immediately after the starting parentheses or you can use put space between them. This means that printf("") is valid, so is printf( ""), so is printf ("" ), so is printf( "" ), so is printf( ""), and so is printf ( "" ).
In the double-quotes inside the parentheses of printf(), type % followed by a special character. There are only some special characters you can use and we will see which ones. Optionally, you can write anything you want before and/or after %special-character. If you judge it necessary, you can put empty spaces before and after the %special-character. Those empty spaces will display as empty spaces on the screen.
After the right double-quotes, type a comma. You can put any number of empty spaces before and after the comma. Those empty spaces will not display. After the comma, type the name of the variable. You can put any number of empty spaces before and after the name of the variable, which also means that you can put empty spaces between the name of the variable and the closing parentheses. Those empty spaces will not display.
A Byte
A Combination of 8 Bits
A byte is a combination of eight adjacent bits. The first bit, located on the most right side, is Bit 0. The last bit, on the most left side, is Bit 7:
Bit 0 is called the least significant bit. It is also valled the low order bit or LOBIT. Bit 7 is called the most significant bit. It is also called the high order bit or HIBIT.
If you create different combinations of empty (0) and full (1) objects grouped in eight, in binary formats, you get 00000000, 00000001, 00000010, 00000011, 00000100, 00000101, 00000110, 00000111, 00001000, 00001001, 00001010, 00001011, 00001100, 00001101, 00001110, 00001111, etc, up to 11111111. When a large number is represented in binary format, it can be difficult to read. An alternative is to create groups of four bits so that instead of writing 01001011, you would write 0100 1011.
To evaluate the number of combinations in decimal format, you use the number 2 that represents decimal, you elevate it to the power of the position of the bit (0, 1, 2, 3, 4, 5, 6, or 7), and you add the number. This can be done as follows:
27 + 26 + 25 + 24 + 23 + 22 + 21 + 20 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255
Therefore, we 255 possible combinations of eight bits. The combinations can also be represented in hexadecimal format as 0x1, 0x2, ..., 0xA, 0xA1, ..., 0xC8, ..., up to 0xFFFF.
In the three numeric systems, we get:
Decimal | Hexadecimal | Binary | |
Minimum | 0 | 0x0 | 0000 |
Maximum | 255 | 0xff | 1111 1111 |
Introduction to Characters
The minimum storage area offered by the computer (Intel, AMD, etc, processors) is the byte. As you know already, a byte is a group of 8 consecutive bits. The amount of memory space offered by a byte can be used to store just a single symbol, such as those you see on your keyboard. These symbols, also called characters, have been organized by the American Standard Code for Information Exchange (ASCII) in a set list. But, ASCII uses only 128 decimal numbers (based on a 7-bit format) to represent symbols counted from 0 to 127. To compensate for the remaining 1 bit, IBM used it to organize special characters, foreign language characters, mathematical symbols, small graphics, etc. Each one of these characters has a decimal, a hexadecimal, and a binary equivalents. Some of the characters are: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z. Besides these readable characters, the following symbols are called digits and they are used to represent numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. In addition, some symbols on the (US QWERTY) keyboard are also called characters or symbols. They are ` ~ ! @ # $ % ^ & * ( ) - _ = + [ { ] } \ | ; : ' < ? . / , > ".
To declare a variable that would hold a character, use a keyword named char. To specify the value of the variable, put its character in single quotes. Here is an example:
#include <stdio.h>
void main()
{
char c = 'm';
}
Remember that you can also use the auto keyword to declare the variable and you must initialize the variable with a character in single-quotes.
Displaying a character
To display the value of a char or of a wchar_t variable, use the c special character. Here is an example:
#include <stdio.h> void main() { char c = 'f'; printf("%c", c); }
As mentioned previously, you can add other things before % and/or after the special character. Here is an example:
#include <stdio.h> void main() { char c = 'f'; printf("Gender: %c", c); }
This would produce:
Gender: f
Escape Sequences
An escape sequence is a special character that displays non-visibly. For example, you can use this type of character to indicate the end of line, that is, to ask the program to continue on the next line. An escape sequence is represented by a backslash character, \, followed by another character or symbol. For example, the escape sequence that moves to the next line is \n. The escape sequences are:
Escape Sequence | Name | Description |
\a | Bell (alert) | Makes a sound from the computer |
\b | Backspace | Takes the cursor back |
\t | Horizontal Tab | Takes the cursor to the next tab stop |
\n | New line | Takes the cursor to the beginning of the next line |
\v | Vertical Tab | Performs a vertical tab |
\f | Form feed | |
\r | Carriage return | Causes a carriage return |
\" | Double Quote | Displays a quotation mark (") |
\' | Apostrophe | Displays an apostrophe (') |
\? | Question mark | Displays a question mark |
\\ | Backslash | Displays a backslash (\) |
\0 | Null | Displays a null character |
You can include an escape sequence inside the double-quotes of printf(). Here is an example:
#include <stdio.h>
void main()
{
char c = 'f';
printf("School Registration\nGender: %c", c);
}
This would produce:
School Registration Gender: f
To use an escape sequence, you can also first declare a char variable and initialize it with the desired escape sequence in single-quotes.
Primary Details on Variables
Declaring many Variables
If you are planning to use many variables, you can declare each on its line. Here are examples:
char category; char gender; char membership;
If you are declaring variables that are of the same type, you can write their common data type once, then write the name of each variable, separate them with commas, and end the statement with a semicolon. Here is an example:
char category, gender; char membership;
Updating a Variable
After declaring a variable and optionally using it, at any time, you can change its value. To do this, type the name of the variable and assign a (new) value to it. Here are examples:
#include <stdio.h> void main() { char membership; char membership = 'W'; printf("Membership: %c\n", membership); membership = 'P'; printf( "Membership: %c", membership); }
This would produce:
Membership: W Membership: P
Displaying Many Values
To display different values of a program, you can use printf() for each. Here are examples:
#include <stdio.h> void main() { char gender = 'F'; char category = 'T'; printf( "Member Gender: %c", gender); printf(" "); printf( "of a %c category", category); }
This would produce:
Member Gender: F of a T category
Constants
A constant is a variable whose value cannot change. When declaring the variable, you must indicate that its value cannot be updated. To support this, start the declaration with the const keyword. Specify the type of the variable and a name. You must also initialize the variable. Here are examples:
#include <stdio.h> void main() { const char gender = 'F'; const char category = 'T'; }
After declaring a constant variable and initializing it, if you change its value, when the program is built, you would receive an error. As a esult, the following program will produce an error:
#include <stdio.h> void main() { const char membership = 'W'; printf( "Membership: %c\n", membership ); membership = 'P'; printf("Membership: %c", membership); }
Of course, you can display the value of the constant variable using printf().Here are examples:
#include <stdio.h> void main() { const char gender = 'F'; const char category = 'T'; printf("Member Gender: %c", gender); printf(" "); printf("of a %c category", category); }
Overview
A string is 0 or a group of symbols. To indicate that it is a string, you should include an empty space or the symbols in double-quotes. This means that the value of a string starts with a double-quote and ends with a double-quote. An example of a string is "Welcome to Application Programming!".
Introduction to String Variables
A string can be stored in a variable. The primary formula to declare a variable for a string is:
char * variable-name;
Start with char * followed by the name of the variable. Notice that you must use an asterisk between char and the name of the variable. The expression char * is considered the data type of the variable (in later lessons, we will find out what the asterisk actually means). The position of the asterisk is not important as long as it is between char and the name of the variable. This means that the asterisk can touch the data type or the variable, or the asterisk can stand by itself. Here are examples:
#include <stdio.h>
void main()
{
char* strFirstName;
char * strLastName;
char *strFullName;
}
Initializing a String Variable
To initialize a string variable, put its value in double-quotes and assign it to the variable. Here are examples:
#include <stdio.h>
void main()
{
char* strFirstName = "Paul";
char * strMiddleName = "Bertand";
char *strLastName = "William";
}
The number of characters of a string is referred to as the length of the string. The maximum number of characters you can put in a string variable may depend on the compiler you are using. Normally, you can put up to 509 characters. If you are using the Microsoft C compiler, you can use up to 2047 characters.
Displaying a String
To display the value of a string variable, in the double-quotes of printf(), use %s. Here are examples:
#include <stdio.h> void main() { char* strFirstName = "Paul"; char * strMiddleName = "Bertand"; char *strLastName = "William"; printf("Full Name: %s", strFirstName); printf(" %s ", strMiddleName); printf("%s", strLastName); }
This would produce:
Full Name: Paul Bertand William
Speaking of strings, besides printf, you can also use printf_s. Use both exactly the same way. Here are examples:
#include <stdio.h>
void main()
{
char* strFirstName = "Antoinette";
char* strMiddleName = "Julie";
char* strLastName = "Rothingham";
printf("Full Name: %s", strFirstName);
printf_s(" %s ", strMiddleName);
printf_s("%s", strLastName);
}
This would produce:
Full Name: Antoinette Julie Rothingham Press any key to close this window . . .
Primary Operations on Strings
Escpape Sequences
Strings support escape sequence. As seen with printf(), to include an escape sequence in a string, simply type it inside any part of the string. Here is an example:
#include <stdio.h> void main() { char* strFirstName = "Paul"; char * strMiddleName = "Bertand"; char *strLastName = "William"; char* address = "9248 Green Holly Road\nRockville, MD 20856"; printf("%s", strFirstName); printf_s(" %s ", strMiddleName); printf("%s\n", strLastName); printf_s("%s", address); }
This would produce:
Paul Bertand William 9248 Green Holly Road Rockville, MD 20856 Press any key to close this window . . .
Updating a String Variable
After declaring a variable for a string, at any time, you can set or change its value. To do this, type the name of the variable and assign the desired value to it (remember that the string variable must be included in double-quotes). Here are examples:
#include <stdio.h> void main() { char* strFirstName = "Paul"; char * strMiddleName = "Bertand"; char *strLastName = "William"; char* address = "9248 Green Holly Road\nRockville, MD 20856"; printf_("%s", strFirstName); printf(" %s ", strMiddleName); printf_("%s\n", strLastName); printf("%s", address); printf_("\n-------------------------\n"); strFirstName = "Julianne"; strLastName = "Delance"; address = "10372 Hill Craters Court, Suite #D6\nFairview, TN 37060"; printf("%s", strFirstName); printf_(" %s\n", strLastName); printf("%s", address); }
This would produce:
Paul Bertand William 9248 Green Holly Road Rockville, MD 20856 ------------------------- Julianne Delance 10372 Hill Craters Court, Suite #D6 Fairview, TN 37060
String Alignment
When you display the value of a string variable, you can specify how to align the value from the left border of the screen. To do this, between % and s, type the desired number of empty character spaces. Here are examples:
#include <stdio.h> void main() { char* strFirstName = "Paul"; char * strMiddleName = "Bertand"; char *strLastName = "William"; char* street = "9248 Green Holly Road"; char * location = "Rockville, MD 20856"; printf("First Name: %5s\n", strFirstName); printf("Middle Name: %5s\n", strMiddleName); printf("Last Name: %9s\n", strLastName); printf("Address: %25s\n", street); printf("%32s", location); }
This would produce:
First Name: Paul Middle Name: Bertand Last Name: William Address: 9248 Green Holly Road Rockville, MD 20856 Press any key to close this window . . .
A Constant String
When you declare a string variable, you and optionally start the declaration with the const keyword. You can initialize or not initialize the variable. Here are examples:
#include <stdio.h> void main() { const char* strFirstName; char * strMiddleName = "Matthew"; const char *strLastName; char* street = "2948 Suess Road #204"; const char * location; strLastName = "Feuer"; strFirstName = "Christopher"; location = "Mundaring Western Australia 6073"; printf("First Name: %12s\n", strFirstName); printf("Middle Name: %s\n", strMiddleName); printf("Last Name: %7s\n", strLastName); printf("Address: %24s\n", street); printf("%45s", location); printf("\n--------------------------------------------------\n"); strFirstName = "Clarice"; strLastName = "Nathanson"; street = "951 Wellington Ave"; location = "Regina, SK S4N 0R7"; printf("Full Name: %9s", strFirstName); printf(" %s\n", strLastName); printf("Address: %22s\n", street); printf("%31s", location); printf("\n==================================================="); }
This would produce:
First Name: Christopher Middle Name: Matthew Last Name: Feuer Address: 2948 Suess Road #204 Mundaring Western Australia 6073 -------------------------------------------------- Full Name: Clarice Nathanson Address: 951 Wellington Ave Regina, SK S4N 0R7 ===================================================
If you are not planning to change the value of a string variable, you can indicate that it is a constant. To do this, type the const keyword between the asterisk and the name of the variable. This time, you must initialize the variable, and you cannot change the value of the variable after that. Consider this code:
#include <stdio.h> void main() { const char* strFirstName; char * const strMiddleName = "Matthew"; const char *strLastName; char* const street = "2948 Suess Road #204"; const char * location; strLastName = "Feuer"; strFirstName = "Christopher"; location = "Mundaring Western Australia 6073"; printf("First Name: %12s\n", strFirstName); printf("Middle Name: %s\n", strMiddleName); printf("Last Name: %7s\n", strLastName); printf("Address: %24s\n", street); printf("%45s", location); printf("\n--------------------------------------------------\n"); strFirstName = "Clarice"; strLastName = "Nathanson"; street = "951 Wellington Ave"; location = "Regina, SK S4N 0R7"; printf("Full Name: %9s", strFirstName); printf(" %s\n", strLastName); printf("Address: %22s\n", street); printf("%31s", location); printf("\n==================================================="); }
This code will produce an error when the compiler reaches the line that tries to change the value of the strMiddleName variable or of the street variable because they were made constant.
Creating a Long String
When creating a string, if it is long, you can spread it to more than one line. You have two primary options:
#include <stdio.h>
void main()
{
const char* strFirstName = "Jennifer";
char * const strMiddleName = "Rosalina";
const char *strLastName = "Bingham";
char* const address = "9247 Southern Susquehanna Boulevard, \
Winston-Salem, North Carolina 27101";
printf("First Name: %s\n", strFirstName);
printf("Middle Name: %s\n", strMiddleName);
printf("Last Name: %s\n", strLastName);
printf("Address: %s", address);
printf("\n===================================================");
}
This would produce:
First Name: Jennifer Middle Name: Rosalina Last Name: Bingham Address: 9247 Southern Susquehanna Boulevard, Winston-Salem, North Carolina 27101 =================================================== Press any key to close this window . . .If you use the backslash to delimit the sub-string, in most cases, each subsequent line should start in the beginning of its line. This is because the compiler considers that any space between the backslash and the next line most be kept (that is, that space must be used as space)
#include <stdio.h>
void main()
{
const char* strFirstName = "Jennifer";
char * const strMiddleName = "Rosalina";
const char *strLastName = "Bingham";
char* const address = "9247 Southern Susquehanna Boulevard, "
"Winston-Salem, North Carolina 27101";
printf("First Name: %s\n", strFirstName);
printf("Middle Name: %s\n", strMiddleName);
printf("Last Name: %s\n", strLastName);
printf("Address: %s", address);
printf("\n===================================================");
}
This time, the compiler considers the string continues from one double-quote to the next double-quoteA Word
A word is a group of 16 consecutive bits. The bits are counted from right to left starting at 0:
Considered as a group of 16 bits, the most right bit of a word, bit 0, is called the least significant bit or low order bit or LO bit or LOBIT. The most left bit, bit 15, is called the most significant bit or high order bit or HI bit or HIBIT. The other bits are referred to using their positions: bit 1, bit 2, bit 3, etc.
Considering that a word is made of two bytes, the group of the right 8 bits is called the least significant byte or low order byte or LO byte or LOBYTE. The other group is called the most significant byte or high order byte or HI byte or HIBYTE.
The representation of a word in binary format is 0000000000000000. To make it easier to read, you can group bits by 4, like this: 0000 0000 0000 0000. Therefore, the minimum binary value represented by a word is 0000 0000 0000 0000. The minimum decimal value of a word is 0. The minimum hexadecimal value you can store in a word is 0x0000000000000000. This is also represented as 0x00000000, or 0x0000, or 0x0. All these numbers produce the same value, which is 0x0.
The maximum binary value represented by a word is 1111 1111 1111 1111. To find out the maximum decimal value of a word, you can use the base 2 formula, filling out each bit with 1:
1*215+1*214+1*213 + 1*212 + 1*211 + 1*210 + 1*29 + 1*28 + 1*27 + 1*26 + 1*25 + 1*24 + 1*23 + 1*22 + 1*21 + 1*20
= 32768 + 16384 + 8192 + 4096 + 2048 + 1024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1
= 65535
To find out the maximum hexadecimal number you can store in a word, replace every group of 4 bits with an f or F:
1111 | 1111 | 1111 | 1111 | ||||
f | f | f | f | ||||
|
Wide Characters
If you are creating an application for an audience that uses a Latin-based language (English, French, Spanish, etc), most of the characters you will use may be from the alphabet of one of those languages. As stated above, the characters of those languages need only 8 bits of the computer memory. Of course, there exist many languages in the world and they use different types of characters. To be able to handle all types of characters of any language, the computer makes available 16 bits of memory to store a character. As a result, the computer uses a wide-character scheme that can accommodate more than 60000 characters.
Todeclare a variable that can store any type of character, use a data type named wchar_t. Here is an example:
#include <stdio.h>
void main()
{
wchar_t c = 'f';
}
The variable of the variable can be included in single-quotes. Here is an example:
#include <stdio.h>
void main()
{
wchar_t c = 'f';
}
Optionally, to indicate that you want the compiler to use 16 bits to store the value of the variable, start its value with L. Here is an example:
#include <stdio.h>
void main()
{
wchar_t c = L'f';
}
Other than that, to display the value of a wide-character variable, in the double-quotes of print(), use %c.
Introduction to Natural Numbers
A word, which is a group of 16 contiguous bits or 2 bytes, can be used to hold a natural number. As we have studied, the maximum numeric value that can fit in a word is 65535. To declare a variable that can hold a value of two bytes, use the short keyword. Here is an example:
#include <stdio.h>
void main()
{
short s;
}
To specify the initial value of the variable, assign a value between -32768 et 32767 to the variable.
Remember that you can declare any variable using the auto keyword. In this case, you must initialize the variable.
Displaying the Value of an Integer
To display the value of an integer, in the double-quotes of the parentheses of printf(), use %i. Here is an example:
#include <stdio.h> void main() { short distance = 316; printf("Distance: %i miles", distance); }
This would produce:
Distance: 316 miles
Besides %i, you can use %d to display the value of an integer. Here is an example:
#include <stdio.h> void main() { short distance = 316; short length = 9408; printf("Distance: %i miles\n", distance); printf("Length: %d units", length); }
This would produce:
istance: 316 miles Length: 9408 units
A Double-Word
Introduction
Remember that a byte represents 16 bits, which is also refered to as a word. You may need to store a large number that needs more than 16 bits. In this case, you can use two Words, which is equivalent to 2 x 16 bits = 32 bits of the computer memory. A combination of two Words is referred to as a double-word.
A double-word is a group of two consecutive words. This means that a double-word combines 4 bytes or 32 bits. The bits, counted from right to left, start at 0 and end at 31. The most right bit, bit 0, is called the low order bit or LO bit or LOBIT. The most left bit, bit 31, is called the high order bit or HI bit or HIBIT. The other bits are called using their positions.
The group of the first 8 bits (from bit 0 to bit 7), which is the right byte, is called the low order byte, or LOBYTE. The group of the last 8 bits (from bit 24 to bit 31), which is the left byte, is called the high order byte, or HIBYTE. The other bytes are called by their positions. The group of the right 16 bits, or the right Word, is called the low order Word, or LOWORD. The group of the left 16 bits, or the left Word, is called the high order Word, or HIWORD.
The minimum binary number you can represent with a double-word is 0. The minimum decimal value of a double-word is 0. To find out the maximum decimal value of a Word, you can use the base 2 formula giving a 1 value to each bit:
2n-1 | 230 | 229 | 228 | 227 | 226 | 225 | 224 |
etc | 1,073,741,824 | 536,870,912 | 268,435,456 | 134,217,728 | 67,108,864 | 33,554,432 | 16,777,216 |
223 | 222 | 221 | 220 | 219 | 218 | 217 | 216 |
8,388,608 | 4,194,304 | 2,097,152 | 1,048,576 | 524,288 | 262,144 | 131,072 | 65,536 |
215 | 214 | 213 | 212 | 211 | 210 | 29 | 28 |
32,768 | 16,384 | 8,192 | 4,096 | 2,048 | 1,024 | 512 | 256 |
27 | 26 | 25 | 24 | 23 | 22 | 21 | 20 |
128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
1*231+1*230+1*229 + 1*228 + 1*227 + 1*226 + 1*225 + 1*224 + 1*223 + 1*222 + 1*221 + 1*220 + 1*219 + 1*218 + 1*217 + 1*216 + 1*215 + 1*214 + 1*213 + 1*212 + 1*211 + 1*210 + 1*29 + 1*28 + 1*27 + 1*26 + 1*25 + 1*24 + 1*23 + 1*22 + 1*21 + 1*20
= 2,147,483,648 + 1,073,741,824 + 536,870,912 + 268,435,456 + 134,217,728 + 67,108,864 + 33,554,432 + 16,777,216 + 8,388,608 + 4,194,304 + 2,097,152 + 1,048,576 + 524,288 + 262,144 + 131,072 + 65,536 + 32,768 + 16,384 + 8,192 + 4,096 + 2,048 + 1,024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1
= 4,286,578,708
The minimum hexadecimal value you can store in a double-word is 0x00000000000000000000000000000000 which is the same as 0x0. To find out the maximum hexadecimal number you can represent with a word, replace every group of 4-bits with an f or F:
1111 | 1111 | 1111 | 1111 | 1111 | 1111 | 1111 | 1111 |
f | f | f | f | f | f | f | f |
= 0xffffffff = 0xFFFFFFFF |
An Integral Value
To declare a variable that can hold a value between 0 and 4,286,578,708, use a data type named int. Here is an example:
#include <stdio.h>
void main()
{
int items;
}
To initialize the variable, assign a value between 0 and 4,286,578,708 to it. On the otther hand, remember that you can declare a variable using the auto keyword, in which case you must initialize it. Here is an example:
#include <stdio.h>
void main()
{
int items;
auto mean = 3080;
}
Primary Characteristics of Integers
The Size of a Variable
As we have mentioned previously, you will use different amounts of computer memory to store different values. At any time when using a variable, you may want to know how much computer memory it is using. To get this information, use an operator named sizeof. The formula to use this operator is:
sizeof(variable-name)
The sizeof() variable produces the number of bytes that a variable is using to store its value. To get that number, put the name of the variable in the parentheses are sizeof(). You can then assign it to an integer variable. As always, to display the value of that integer variable, in the double-quotes of printf(), use %i or %d. Here is an example:
#include <stdio.h>
void main()
{
short salary = 31405;
printf("Yearly Salary: $%d", salary);
printf(" ");
printf("uses %i byte(s)", sizeof(salary));
}
This would produce:
Yearly Salary: $31405 uses 2 byte(s)
One of the characteristics of a number is to indicate whether it is lower than 0, equal to 0, or higher than 0. A number that is lower than 0 is said to be negative. Such a number must be preceded by -. If a number is higher than 0, it is said to be positive. Such a number can be preceded by + or no sign. The ability for a number to hold a sign makes it possible to say that such a number is signed. It is important to know that, when a number is said to be signed, that number can be negative or positive. As seen in our previous calculations, the value of such a variable is between -2,147,483,648 and 2,147,484,647. When specifying the value of the variable, if the value is negative, you must start it with the - symbol. If the value is positive, you can start it with + or omit the symbol.
When declaring a variable, to indicate that it can hold negative or positive integral numbers, use the signed data type. Here is an example:
#include <stdio.h>
void main()
{
signed salary = 66824;
int size = sizeof(salary);
printf("Yearly Salary: $%i\n", salary);
printf("To hold the salary, we need %d byte(s)", size);
}
This would produce:
Yearly Salary: $66824 To hold the salary, we need 4 byte(s)
As an alternative, to declare a variable for a signed integerr, you can use the signed int data type. Here are examples:
#include <stdio.h>
void main()
{
signed int number_of_pages;
signed int temperature;
number_of_pages = 842;
temperature = -1544;
printf("Number of Pages of the book: %i\n", number_of_pages);
printf("Temperature to reach during the experiment: %i degrees", temperature);
}
When executed, the program would produce:
Number of Pages of the book: 842 Temperature to reach during the experiment: -1544 degrees Press any key to close this window . . .
When you write a number, if you don't add a symbol sign to it, the number is considered positive. Because has neither a - nor a + symbol, the number is said to be unsigned. Normally, the 0 number doesn't use a sign. The uint keyword is used for a variable that can hold a number between 0 and 4,294,967,295 (the commas here are used only to make the number easy to read).
When declaring a variable, if you want to indicate that you want the varialbe to hold positive natural numbers, declare that variable using the unsigned data type. Here is an example:
#include <stdio.h>
void main()
{
unsigned n = 39273;
printf("Number: %i", n);
}
This would produce:
Number: 39273
As an alternative, to declare a variable for a large positive positive natural number, use the unsigned int data type. To display the value of the variable, use %d or %i Here are examples:
#include <stdio.h>
void main()
{
unsigned int day_of_birth;
unsigned int month_of_birth;
unsigned int year_of_birth;
day_of_birth = 8;
month_of_birth = 11;
year_of_birth = 2016;
printf("Red Oak High School\n");
printf("Student Date of Birth: %d", month_of_birth);
printf("/");
printf("%i", day_of_birth);
printf("/");
printf("%d", year_of_birth);
}
This would produce:
Red Oak High School Student Date of Birth: 11/8/2016
As seen previously, a short integer is a number between -32768 and 32767. To declare a variable for such a number, use the short keyword or the signed short data type. Here are examples:
#include <stdio.h>
void main()
{
signed short number_of_pages;
signed short temperature;
number_of_pages = 842;
temperature = -1544;
printf("Number of Pages of the book: %i\n", number_of_pages);
printf("Temperature to reach during the experiment: %i degrees", temperature);
}
This would produce:
Number of Pages of the book: 842 Temperature to reach during the experiment: -1544 degrees
If a variable must hold positive and relatively small numbers, it is referred as an unsigned short integer. To declare such a variable, use the unsigned short data type. An unsigned short integer can hold numbers that range from 0 to 65535 and therefore can fit in 16 bits. Here is an example that uses an unsigned short variable:
#include <stdio.h>
void main()
{
unsigned short n = 8482;
int s1 = sizeof(n);
unsigned t = 14200;
int s2 = sizeof(t);
printf("Number %i ", n);
printf("needs %i bytes\n", s1);
printf("Number %i ", t);
printf("needs %i bytes", s2);
}
This would produce:
Number 8482 needs 2 bytes Number 14200 needs 4 bytes
Hexadecimal Numbers
Remember that one way to express a number is in the hexadecimal format. It uses a combination of the first 6 letters of the English alphabet (a, b, c, d, e, and f or A, B, C, D, E, or F) and the 10 digits. The number starts with 0x. Here is an example:
#include <stdio.h>
void main()
{
unsigned int number = 0xF0488EA;
printf("Number: %i", number);
}
This would produce:
Number: 251955434
When declaring a variable that will hold a regular symbol, to indicate that its value should be between -128 and 127, declared it using the signed signed char data type.
If you are declaring a variable for a regular character and you want to indicate that the character is from 0 to 255, using the unsigned char data type to declare the variable.
A Long Integer
As an alternative to
#include <stdio.h>
void main()
{
long large;
}
Initializing a Long Integer
To initialize a variable declared with the long data type, you can assign the same types of numbers we saw for integers. Here are examples:
#include <stdio.h> void main() { long number1 = 384706495; long number2 = 630495373; printf("Number: %d\n", number1); printf("Number: %i", number2); }
This would produce:
Number: 384706495 Number: 630495373
When initializing a long variable, as an option, to indicate that the variable is holding not just a a regular natural number but a long integer, end its value with l or L. Here are examples:
#include <stdio.h>
void main()
{
long number1 = 384706495l;
long number2 = 630495373L;
printf("Number: %d\n", number1);
printf("Number: %i", number2);
}
Displaying the Value of a Long Integer
As an option, to display the value of a long integer, in the double-quotes of printf(), use %ld or %li. Here are examples:
#include <stdio.h> void main() { long ancient = 1885; auto much = 30495373; long know = 60394; printf("Number: %d\n", ancient); printf("Number:%i\n", much); printf("Number: %ld", know); }
When you decide to use a variable that can hold a small to large number, you may want the number to be positive or negative. We have already seen that such a number is said to be "signed". To indicate that you want the varible to hold a positive or negative number, you can declare it using the signed long data type. Here are examples:
#include <stdio.h> void main() { long ancient = 1885L; auto much = 30495373L; long know = 60394L; signed long large = -472930416; printf("Number: %d\n", ancient); printf("Number: %i\n", much); printf("Number: %ld\n", know); printf("Number: %li", large); }
This would produce:
Number: 1885 Number: 30495373 Number: 60394 Number: -472930416
As mentioned for other integral types, you can initialize a long or a signed long (or an auto) variable (that holds a long integer) with a hexadecimal value.
You can use a combination of 32 bits to store positive or negative integers. In some cases, you will need a variable to hold only positive numbers. We saw that when you don't apply the - symbol on a number, the number is said to be un-signed. Such a number is automatically treated as positive. To declare a variable for such a number, you can use the unsigned long data type. A variable declared as unsigned long can handle small to large positive numbers. Initialize the variable with a positive natural number of any value. Here is an example:
#include <stdio.h> void main() { int n1 = 1885; int s1 = sizeof(n1); auto n2 = 304953273; int s2 = sizeof(n2); long n3 = -472930416; int s3 = sizeof(n3); signed long n4 = 92832425; int s4 = sizeof(n4); unsigned long n5 = 730468079; int s5 = sizeof(n5); printf("Ancient Integer: %i. ", n1); printf("It uses: %i bytes\n", s1); printf("Auto Number: %d. ", n2); printf("It uses: %i bytes\n", s2); printf("Long Number: %li. ", n3); printf("It uses: %i bytes\n", s3); printf("Signed Long Number: %ld. ", n4); printf("It uses: %i bytes\n", s4); printf("Signed Long Number: %i. ", n5); printf("It uses: %i bytes", s5); }
This would produce:
Ancient Integer: 1885. It uses: 4 bytes Auto Number: 304953273. It uses: 4 bytes Long Number: -472930416. It uses: 4 bytes Signed Long Number: 92832425. It uses: 4 bytes Signed Long Number: 730468079. It uses: 4 bytes
As an option, when indicating the value an unsigned long integer, you can end that value with lu or
#include <stdio.h> void main() { int n1 = 1885; int s1 = sizeof(n1); auto n2 = 304953273; int s2 = sizeof(n2); long n3 = -472930416; int s3 = sizeof(n3); unsigned long n4 = 92832425ul; int s4 = sizeof(n4); unsigned long n5 = 730468079UL; int s5 = sizeof(n5); printf("Ancient Integer: %i. ", n1); printf("It uses: %i bytes\n", s1); printf("Auto Number: %d. ", n2); printf("It uses: %i bytes\n", s2); printf("Long Number: %li. ", n3); printf("It uses: %i bytes\n", s3); printf("Signed Long Number: %ld. ", n4); printf("It uses: %i bytes\n", s4); printf("Signed Long Number: %i. ", n5); printf("It uses: %i bytes", s5); }
Introduction
Sometimes you may want to store values that a double-word cannot handle. To store a very large number in a variable, you can double a double-word. The group can be referred to as a quad-word. A quad-word is a double double-word. In other words, a quad-word combines 2 * double-word = 2 * 2-word = 2 * 2 * 16 bits = 2 * 32 bits or 4 * 16 bits = 64 bits. Based on calculations like we did previously, 64 bits would produce a very large number. A quad-word is so large that it can store numbers in the range of -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807.
When you decide to use a variable that can hold a small to very large number, you may want the number to be positive or negative. We saw that such a number is said to be "signed". To indicate that you want your varible to hold small to large positive or negative numbers, you can declare it using the long long data type. Such a variable can hold numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807.
To display the value of a long long variable, in the double-quotes of printf(), use %lli or %lld. Here is an example:
#include <stdio.h> void main() { int n1 = 1885; int s1 = sizeof(n1); auto n2 = 304953273; int s2 = sizeof(n2); long long n3 = 9280749574975; int s3 = sizeof(n3); printf("Natural Number: %i. ", n1); printf("It uses: %i bytes\n", s1); printf("Auto Number: %d. ", n2); printf("It uses: %i bytes\n", s2); printf("Long Number: %lli. ", n3); printf("It uses: %i bytes", s3); }
This would produce:
Natural Number: 1885. It uses: 4 bytes Auto Number: 304953273. It uses: 4 bytes Long Number: 9280749574975. It uses: 8 bytes
A Long Long Integer
As an option, to declare a variable that can hold very large natural numbers, you can use the long long int data type.
A Signed Long Long Integer
An alternative to declare a variable that can use small to very large natural number is to use the signed long long data type. Here is an example:
#include <stdio.h>
void main()
{
int n1 = 1885;
int s1 = sizeof(n1);
auto n2 = 304953273;
int s2 = sizeof(n2);
signed long long n3 = 9280749574975;
int s3 = sizeof(n3);
printf("Natural Number: %i. ", n1);
printf("It uses: %i bytes\n", s1);
printf("Auto Number: %d. ", n2);
printf("It uses: %i bytes\n", s2);
printf("Long Number: %lli. ", n3);
printf("It uses: %i bytes", s3);
}
An Unsigned Long Long Integers
If you want your 64-bit variable to hold only positive integers, you can declare using the unsigned long long data type. A variable declared as unsigned long long can handle small to extremely large positive numbers from 0 to 18,446,744,073,709,551,615. Initialize the variable with a positive natural number of any value. Here is an example:
#include <stdio.h>
void main()
{
int n1 = 1885;
int s1 = sizeof(n1);
auto n2 = 304953273;
int s2 = sizeof(n2);
long n3 = -472930416;
int s3 = sizeof(n3);
signed long n4 = 92832425;
int s4 = sizeof(n4);
unsigned long long n5 = 730468079;
int s5 = sizeof(n5);
printf("Ancient Integer: %i. ", n1);
printf("It uses: %i bytes\n", s1);
printf("Auto Number: %d. ", n2);
printf("It uses: %i bytes\n", s2);
printf("Long Number: %li. ", n3);
printf("It uses: %i bytes\n", s3);
printf("Signed Long Number: %ld. ", n4);
printf("It uses: %i bytes\n", s4);
printf("Signed Long Number: %lli. ", n5);
printf("It uses: %i bytes", s5);
}
An Unsigned Long Long Integer
As an option, to declare a variable for a huge positive natural number, you can use the unsigned long int or the unsigned long long int data type.
Introduction to Floating-Point Numbers
Overview
A floating-point number is a number that may include an approximation. To make this possible, the number is made of two sections separated by a symbol that is referred to as the Decimal Separator or Decimal Symbol. This symbol is different by language, country, group of languages, or group of countries. In US English, this symbol is the period as can be verified from the Regional (and Language) Settings of the Control Panel:
The left side holds that numeric natural side of the number. In some cases, that side would be enough to represent the number. In this case, such a number is the same as an integer.
The most fundamental way to declare a variable that would hold a floating-point number is to use a keyword named float. Here is an example:
#include <stdio.h>
void main()
{
float number;
}
To specify the value of a floating-point number, if you want to present the number as a natural one, provide its value the same way we saw for integers. Otherwise, a floating-point number can have a second part on the right side after the decimal separator. Normally, that right side can have as many digits as you want. Here are examples:
#include <stdio.h>
void main()
{
float value = 4857;
float number = 928.427972416;
float represent = -6827.468;
}
Displaying a Floating-Point Number
Introduction
The character to use to display the value of a floating-point variable is f, in which case you would use %f. This time, you are supposed to format the number a certain way. This means that you should specify how the number should be displayed. To do this, between % and f, you will specify a numeric alignment and a precision. The formula to use is alignment.precision. We will come back to the alignment. For now, specify it as 0.
The Precision to Display a Number
After the period of the numeric format, type a constant integer, normally smaller than 32. If the variable is holding a number that resembles an integer, specify the precision as 0. If the number includes a decimal part but you don't want to display that part, specify the precision as 0. Here are examples:
#include <stdio.h> void main() { float value = 4857; float number = 928.427972416; float represent = -6827.468; printf("Value: %0.0f\n", value); printf("Number: %0.0f\n", number); printf("Numeral: %0.0f", represent); }
This would produce:
Value: 4857 Number: 928 Numeral: -6827
If you want to display only one digit in the fractional part, use %0.1f as the format. If the value of the variable is a natural number, it would be displayed with .0. Here are examles:
#include <stdio.h> void main() { float value = 4857; float number = 928.427972416; float represent = -6827.468; printf("Value: %0.1f\n", value); printf("Number: %0.1f\n", number); printf("Numeral: %0.1f", represent); }
This would produce:
Value: 4857.0 Number: 928.4 Numeral: -6827.5
In the same way, if you want to display two digits after the decimal separator, use the format as %0.2f. If the number is natural, it would display with .00. If you want to display the number with three digits, use %0.3f. If you want the number to display four digits, use %0.4f, and so on.
The Default Precision to Display a Number
The default precision is with six digits. If you want to display a number with six digits, omit the alignment.precision and simply use %f as the format. Here are examples:
#include <stdio.h> void main() { float value = 4857; float number = 928.427972416; float represent = -6827.468; printf("Value: %f\n", value); printf("Number: %f\n", number); printf("Numeral: %f", represent); }
This would produce:
Value: 4857.000000 Number: 928.427979 Numeral: -6827.467773
Aligning a Number
When displaying a value, you can ask the compiler to use a certain amount of space to accommodate the number, including its precision. To provide this information, specify a number on left side of the period of the format. Here are examples:
#include <stdio.h> void main() { float value = 4857; float number = 928.427972416; float represent = -6827.468; printf("Value: %8.0f\n", value); printf("Number: %17.10f\n", number); printf("Numeral: %11.4f", represent); }
This would produce:
Value: 4857 Number: 928.4279785156 Numeral: -6827.4678
The Precision of a Floating-Point Number
A Floating-Point Number with Single-Precision
Floating-point numbers are categorized for the level of precision they need. At the most basic level, if you just want a decimal number, we saw that you can declare it using the float keyword. This data type uses 32 bits (which is 4 bytes) to store its value. The value must range from ±1.5 x10−45 to ±3.4 x 1038 with a precision of 7 digits. Here are examples we saw already:
#include <stdio.h> void main() { float value = 4857; float number = 928.427972416; float represent = -6827.468; int s1 = sizeof(value); int s2 = sizeof(number); int s3 = sizeof(represent); printf("Value: %8.0f ", value); printf("uses %d bytes\n", s1); printf("Number: %17.10f ", number); printf("uses %d bytes\n", s2); printf("Numeral: %11.4f ", represent); printf("uses %d bytes", s3); }
This would produce:
Value: 4857 uses 4 bytes Number: 928.4279785156 uses 4 bytes Numeral: -6827.4678 uses 4 bytes
A Floating-Point Number with Double-Precision Numbers
If you want to use a variable that can hold small to very large numbers, declare it using a keyword named double. You can initialize the variable the same way we did for the float type. To display the value, you can use the same formats we used for the float type. Here are examples:
#include <stdio.h> void main() { double value = 4857; double number = 928.427972416; double represent = -6827.468; printf("Value: %8.0f\n", value); printf("Number: %17.10f\n", number); printf("Numeral: %11.4f ", represent); }
This would produce:
Value: 4857 Number: 928.4279724160 Numeral: -6827.4680
The double type is referred to as a floating-point number with double-precision. Its variable uses 64 bits, which is equivalent to 8 bytes. This is demonstrated as follows:
#include <stdio.h> void main() { double value = 4857; double number = 928.427972416; double represent = -6827.468; int s1 = sizeof(value); int s2 = sizeof(number); int s3 = sizeof(represent); printf("Value: %8.0f ", value); printf("uses %d bytes\n", s1); printf("Number: %17.10f ", number); printf("uses %d bytes\n", s2); printf("Numeral: %11.4f ", represent); printf("uses %d bytes", s3); }
This would produce:
Value: 4857 uses 8 bytes Number: 928.4279724160 uses 8 bytes Numeral: -6827.4680 uses 8 bytes
A variable declared as double can store a very large numbers ranging from ±5.0 x 10−324 to ±1.7 x 10308 with a precision of 15 or 16 digits.
A Long Double Variable
Another option to declare a variable that can hold small to very large decimal numbers is to use a data type named long double. The value of the variable can be a natural or fractional number. To display the value of the variable, use any of the formats we reviewed for floating-point numbers. Here are examples:
#include <stdio.h> void main() { long double number1 = 596.1374; long double number2 = -80304617.4250695; long double number3 = 182736475.068; int s1 = sizeof(number1); int s2 = sizeof(number2); int s3 = sizeof(number3); printf("Number: %f ", number1); printf("uses %d bytes\n", s1); printf("Number: %f ", number2); printf("uses %d bytes\n", s1); printf("Number: %f ", number3); printf("uses %d bytes", s1); }
Initializing a Floating-Point Number
When you are initializing a variable for a floating-point number, if you want the compiler to treat the variable as a single-precision number, specify the value with a precision but end it with either f or an F. Here are examples:
#include <stdio.h>
void main()
{
double value = 4857.0f;
float number = 928.427972416F;
double represent = -6827.468f;
int s1 = sizeof(value);
int s2 = sizeof(number);
int s3 = sizeof(represent);
printf("Value: %8.0f ", value);
printf("uses %d bytes\n", s1);
printf("Number: %17.10f ", number);
printf("uses %d bytes\n", s2);
printf("Numeral: %11.4f ", represent);
printf("uses %d bytes", s3);
}
This would produce:
Number: 596.137400 uses 8 bytes Number: -80304617.425069 uses 8 bytes Number: 182736475.068000 uses 8 bytes
A Floating-Point Value With Exponent
When giving the value of a float or double type, you can provide the value as an exponent. Here are examples:
#include <stdio.h> void main() { float number1 = 624.749283795e3; double number2 = 941.8527e6; double number3 = 204618527.3727e-2; printf("Number: %f\n", number1); printf("Number: %f\n", number2); printf("Number: %f ", number3); }
This would produce:
Number: 624749.312500 Number: 941852700.000000 Number: 2046185.273727==========================================================
Practical Learning: Using Strings
null but you must not use string?. If not using null, the value given to a string must be included in double-quotes.
Accessory Data Types
The object data type is used to declare a variable whose type is not primarily defined and can be any of the other data types we have introduced. After creating an object variable, you can use its value as you see fit. For example, you can enter the variable in the parentheses of System.Console.Write() or System.Console.WriteLine() to display it in the console window. Here is an example:
class Exercise
{
static void Main()
{
var EmployeeName = "Ernestine Lamb";
object Address = "10244 Lockwood Drive";
System.Console.Write("Employee Name: ");
System.Console.WriteLine(EmployeeName);
System.Console.Write("Home Address: ");
System.Console.WriteLine(Address);
System.Console.WriteLine();
}
}
A variable declared with object can embrace almost any value. This means that, when initializing the variable, you can use any of the types of values we have seen so far. Here are examples:
class Program
{
static void Main()
{
object propertyNumber = "293749";
object propertyType = 'S';
object stories = 3;
object bedrooms = 4;
object value = 425880;
System.Console.WriteLine("=//= Altair Realtors =//=");
System.Console.WriteLine("Properties Inventory");
System.Console.Write("Property #: ");
System.Console.WriteLine(propertyNumber);
System.Console.Write("Property Type: ");
System.Console.WriteLine(propertyType);
System.Console.Write("Stories: ");
System.Console.WriteLine(stories);
System.Console.Write("Bedrooms: ");
System.Console.WriteLine(bedrooms);
System.Console.Write("Market Value: ");
System.Console.WriteLine(value);
}
}
This would produce:
Custom Constants
Suppose you intend to use a number such as 39.37 over and over again. Here is an example:
class Exercise
{
static void Main()
{
double meter, inch;
meter = 12.52D;
inch = Meter * 39.37D;
System.Console.Write(meter);
System.Console.Write("m = ");
System.Console.Write(inch);
System.Console.WriteLine("in\n");
}
}
Here is an example of running the program:
12.52m = 492.9124in
If you use this 39.37 many times in your program, at one time, you may make a mistake and type it as 3937 or 3.937 or else. Consider the following program:
class Exercise { static void Main() { double meter, inch; meter = 12.52D; inch = Meter * 39.37; System.Console.Write(meter); System.Console.Write("m = "); System.Console.Write(inch); System.Console.WriteLine("in\n"); meter = 12.52D; Inch = Meter * 3.937; System.Console.Write(meter); System.Console.Write("m = "); System.Console.Write(inch); System.Console.WriteLine("in\n"); meter = 12.52D; Inch = Meter * 393.7; System.Console.Write(meter); System.Console.Write("m = "); System.Console.Write(inch); System.Console.WriteLine("in\n"); } }
This would produce:
12.52m = 492.9124in 12.52m = 49.29124in 12.52m = 4929.124in
Because of mistakes in the way to represent the number, the same calculation produces different results. To make sure that this is unlikely, you can instead use a variable that holds the value. Then, when you need that value, you can access the variable instead of the value itself. A number such as 39.37 is called a constant.
A constant is a value that never changes such as 244, "ASEC Mimosa", 39.37, or True. These are constant values you can use in your program any time. You can also declare a variable and make it a constant; that is, use it so that its value is always the same.
To create a constant, type the const keyword to its left. When declaring a constant, you must initialize it with an appropriate value. Here is an example:
const double ConversionFactor = 39.37D;
Once a constant has been created and it has been appropriately initialized, you can use its name where the desired constant would be used. Here is an example of a constant variable used various times:
class Exercise { static void Main() { const double conversionFactor = 39.37D; double meter, inch; meter = 12.52D; inch = Meter * ConversionFactor; System.Console.Write(meter); System.Console.Write("m = "); System.Console.Write(inch); System.Console.WriteLine("in\n"); meter = 12.52D; inch = Meter * ConversionFactor; System.Console.Write(meter); System.Console.Write("m = "); System.Console.Write(inch); System.Console.WriteLine("in\n"); meter = 12.52D; inch = Meter * ConversionFactor; System.Console.Write(meter); System.Console.Write("m = "); System.Console.Write(inch); System.Console.WriteLine("in\n"); } }
This would produce:
12.52m = 492.9124in 12.52m = 492.9124in 12.52m = 492.9124in
Notice that, this time, the calculation is more accurate. Also, this time, if you mistype the name of the variable in an operation, you would receive an error, giving you the time to fix it.
To initialize a constant variable, the value on the right side of the assignment operator "=" must be a constant or a value that the compiler can determine as constant. Instead of using a known constant, you can also assign it another variable that has already been declared as constant.
There are two main categories of constants you will use in your programs. You can create your own constant as we saw above. The C# language also provides various constants. Some constants are part of the C# language. Some other constants are part of the .NET Framework. Before using a constant, of course, you must first know that it exists. Second, you must know how to access it. A constant that is part of the C# language can be accessed anywhere in your code (normally, those constant are defined in the System namespace; other constant are defined in various appropriate namespaces).
null: The null keyword is a constant used to indicate that a variable doesn't hold a known value
PI: PI is a constant used as the ratio of the circumference of a circle to its diameter. PI is defined in Math. To use it, you would type Math.PI.
When C# was invented, one of its biggest goals was to avoid some of the difficulties of C/C++. Among them was the use of pointers. C/C++ uses pointers to refer to the area in memory where a value is located. C# highly avoids pointers and takes over memory management as opposed to letting the programmer take care of that aspect of an application. You can still use pointers in C# in extreme cases when you judge them necessary.
Because the C# compiler is in charge of managing the memory used by the values of an application, pointers are said to be unsafe. If you want to use a pointer in your application, you must precede the name of every method that uses unsafe code with the unsafe keyword. Here is an example:
class Exercise
{
unsafe static void Main()
{
int Length = 224;
int *Len = &Length;
System.Console.Write("Length ");
System.Console.WriteLine(Length);
System.Console.Write("Length ");
System.Console.WriteLine(*Len);
System.Console.WriteLine();
Length = 804;
System.Console.Write("Length ");
System.Console.WriteLine(Length);
System.Console.Write("Length ");
System.Console.WriteLine(*Len);
}
}
To compile the application, you must indicate that you are using unsafe code. To do that, use the /unsafe modifier. Here is an example:
csc /unsafe Exercise.cs
To apply this option in Microsoft Visual Studio, on the main menu, you can click Project -> Project Properties... In the Build section, click the Allow Unsafe Code check box:
=================================================================================================A long integer is a number between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. If you want to use a variable that can hold very large numbers, you can declare it using either the long or the var keyword.
If you declare an integer variable using the var keyword and initialize it with a value between 2,147,484,647 and 9,223,372,036,854,775,807, the compiler concludes that the variable is a long integer:
If you initialize the var variable with a value higher than 9,223,372,036,854,775,807, which is too large, the compiler would present an error:
As mentioned for other integral types, you can initialize a long variable with a hexadecimal value.
Although the long data type is used for large numbers, it mainly indicates the amount of space available but you don't have to use the whole space. For example, you can use the long keyword to declare a variable that would hold the same range of numbers as the short, the int, or the uint data types. If you declare a variable as long but use it for small numbers, the compiler would allocate the appropriate amount of space to accommodate the values of the variable. If you insist on using memory for a long integer, when assigning a value to the variable, add an L suffix to it. Here is an example that uses a long variable to store a number that would fit in 32 bits:
class Exercise
{
static void Main()
{
long countryArea;
countryArea = 5638648L;
System.Console.Write("Country Area: ");
System.Console.Write(countryArea);
System.Console.Write("km2\n");
}
}
Therefore, keep in mind that an int, a uint, a short, or a ushort can fit in a long variable.
An unsigned long integer is a positive (very) integer. To declare a variable for such a number, you can use the ulong data type. A variable declared as ulong can handle extremely large positive numbers that range from 0 to 18,446,744,073,709,551,615.
A real number is a number that displays a decimal part. This means that the number can be made of two sections separated by a symbol that is referred to as the Decimal Separator or Decimal Symbol. This symbol is different by language, country, group of languages, or group of countries. In US English, this symbol is the period as can be verified from the Regional (and Language) Settings of the Control Panel:
On both sides of the decimal symbol, digits are used to specify the value of the number. The number of digits on the right side of the symbol determines the precision of the number.
The integers we have used so far have the main limitation of not allowing decimal values. C# supports floating values that would solve this problem. The most fundamental floating variable is declared with the float keyword. A variable declared as float can store real numbers that range from ±1.5 x 10−45 to ±3.4 x 1038 with a precision of 7 digits in 32 bits. Here is an example:
class Exercise
{
static void Main()
{
float distance;
}
}
When a value is larger than the float and requires more precision, you should declare it using either the var or the double keyword.
To provide the value of a real number, start with the whole side, followed by the decimal separator, and ending with the fraction side. Here is an example:
class Exercise
{
static void Main()
{
var number = 0.9023;
System.Console.Write("Number: ");
System.Console.WriteLine(number);
}
}
This would produce:
Number: 0.9023 Press any key to continue . . .
If the whole part of the number is 0, that is a number between 0 and 1, you can omit the 0. Here is an example:
class Exercise
{
static void Main()
{
var number = .9023;
System.Console.Write("Number: ");
System.Console.WriteLine(number);
}
}
A variable declared as double uses very large numbers ranging from ±5.0 x 10−324 to ±1.7 x Â10308 with a precision of 15 or 16 digits. Because the double data type provides a better result with better precision than the float, whenever you declare a variable using either the var or the float keyword and assign it a value, the compiler allocates memory for a double. If you insist on the variable being treated as float, when assigning it a value, add an f or an F suffix to the value. Here is an example:
class Exercise
{
static void Main()
{
float distance;
distance = 248.38F;
System.Console.Write("Distance = ");
System.Console.Write(distance);
System.Console.WriteLine("km\n");
}
}
This would produce:
Distance = 248.38km
On the other hand, if you want a value to be treated with double-precision, add a d or a D suffix to it. Here is an example:
class Exercise
{
static void Main()
{
var number = 62834.9023D;
System.Console.Write("Number: ");
System.Console.WriteLine(number);
}
}
Practical Learning: Using a Double-Precision Variable
class Order { static void Main() { byte? shirts = null; byte? pants = null; ushort? otherItems = null; uint? orderDay = null; uint? orderMonth = null; uint? orderYear = null; double? mondayDiscount = null; shirts = 4; pants = 0; otherItems = 3; orderDay = 15; orderMonth = 7; orderYear = 2002; mondayDiscount = 0.25D; // 25% System.Console.WriteLine("-/- Georgetown Cleaning Services -/-"); System.Console.WriteLine("========================"); System.Console.Write("Order Date: "); System.Console.Write(orderMonth); System.Console.Write('/'); System.Console.Write(orderDay); System.Console.Write('/'); System.Console.WriteLine(orderYear); System.Console.WriteLine("------------------------"); System.Console.WriteLine("Item Type Qty"); System.Console.WriteLine("------------------------"); System.Console.Write("Shirts "); System.Console.WriteLine(shirts); System.Console.Write("Pants "); System.Console.WriteLine(pants); System.Console.Write("Other Items "); System.Console.WriteLine(otherItems); System.Console.WriteLine("------------------------"); System.Console.Write("Monday Discount: "); System.Console.Write(mondayDiscount); System.Console.WriteLine('%'); System.Console.WriteLine("========================"); System.Console.ReadKey(); } }
-/- Georgetown Cleaning Services -/- ======================== Order Date: 7/15/2002 ------------------------ Item Type Qty ------------------------ Shirts 4 Pants 0 Other Items 3 ------------------------ Monday Discount: 0.25% ========================
The decimal data type can be used to declare a variable that would hold a small or significantly large number. You declare such a variable using the decimal keyword. The values stored in a decimal variable can range from ±1.0 x 10−28 to ±7.9 x 1028 with a precision of 28 to 29 digits. Because of this high level of precision, the decimal data type is suitable for currency values.
After declaring a decimal variable, you can initialize it with a natural number. To indicate that the variable holds a decimal value, when initializing it, add an m or an M suffix to its value. Here is an example:
class Exercise { static void Main() { decimal hourlySalary; hourlySalary = 24.25M; System.Console.Write("Hourly Salary = "); System.Console.WriteLine(hourlySalary); System.Console.WriteLine(); } }
This would produce:
Hourly Salary = 24
As seen in previous sections and this one, when declaring and initializing a real variable, the suffix you give to its assigned value indicates to the compiler the actual type of value and the type of memory that would be allocated for the variable:
Consider the following program:
The purpose of this program is to get the division of 560 by 672. This would produce:
560 / 672 = 0 Press any key to continue . . .
Notice that, when such numbers are submitted to the program, the compiler decides that these are integers and the result produces 0. If you write such an equation and want the result to appear as a real number, you must explicitly indicate it to the compiler. One way you can do this consists of adding decimal places to at least one of the numbers. Here is an example:
class Program { static void Main() { System.Console.Write("560 / 672 = "); System.Console.WriteLine(560.00 / 672.00); } }
This time, the compiler will conclude that the value is a floating-point number; but which one? By default, the compiler would apply the double data type. This version of the program would produce:
560 / 672 = 0.833333333333333 Press any key to continue . . .
If you want to indicate that the value is a float, a double, or a decimal, add the appropriate prefix to it: f, F, d, D, m, or M. Here are examples:
class Program { static void Main() { System.Console.Write("560 / 672 = "); System.Console.WriteLine(560F / 672f); } }
This version of the program would produce:
Practical Learning: Using Decimal Values
class Order { static void Main() { byte? shirts = null; decimal? priceOneShirt = null; byte? pants = null; decimal? priceAPairOfPants = null; ushort? otherItems = null; decimal? priceOtherItems = null; uint? orderDay = null; uint? orderMonth = null; uint? orderYear = null; double? mondayDiscount = null; shirts = 5; priceOneShirt = 0.95M; pants = 2; priceAPairOfPants = 1.95M; otherItems = 3; priceOtherItems = 4.55M; orderDay = 15; orderMonth = 7; orderYear = 2002; mondayDiscount = 0.25D; // 25% System.Console.WriteLine("-/- Georgetown Cleaning Services -/-"); System.Console.WriteLine("========================"); System.Console.Write("Order Date: "); System.Console.Write(orderMonth); System.Console.Write('/'); System.Console.Write(orderDay); System.Console.Write('/'); System.Console.WriteLine(orderYear); System.Console.WriteLine("------------------------"); System.Console.WriteLine("Item Type Qty Unit Price"); System.Console.WriteLine("------------------------"); System.Console.Write("Shirts "); System.Console.Write(shirts); System.Console.Write(" "); System.Console.WriteLine(priceOneShirt); System.Console.Write("Pants "); System.Console.Write(pants); System.Console.Write(" "); System.Console.WriteLine(priceAPairOfPants); System.Console.Write("Other Items "); System.Console.Write(otherItems); System.Console.Write(" "); System.Console.WriteLine(priceOtherItems); System.Console.WriteLine("------------------------"); System.Console.Write("Monday Discount: "); System.Console.Write(mondayDiscount); System.Console.WriteLine('%'); System.Console.WriteLine("========================"); System.Console.ReadKey(); } }
-/- Georgetown Cleaning Services -/- ======================== Order Date: 7/15/2002 ------------------------ Item Type Qty Unit Price ------------------------ Shirts 5 0.95 Pants 2 1.95 Other Items 3 4.55 ------------------------ Monday Discount: 0.25% ========================
A date is a unit that measures the number of years, months, or days elapsed in a specific period. A time is a unit that counts the number of seconds that have elapsed since midnight of the day considered. Although dates and times are large subjects that would require a detailed study, at this time, we will consider them in simple terms.
To declare a variable that would hold date or time values, use the DateTime data type.
class Exercise
{
static void Main()
{
DateTime DateHired;
}
}
The .NET Framework sets its starting periodic date to January 1, 0001 at midnight (12:00:00 or 0:00 AM). If not assigned a specific value, the variable is initialized to 1/1/0001 at midnight.
The object data type is used to declare a variable whose type is not primarily defined and can be any of the other data types we have introduced. After creating an object variable, you can use its value as you see fit. For example, you can enter the variable in the parentheses of System.Console.Write() or System.Console.WriteLine() to display it in the console window. Here is an example:
class Exercise
{
static void Main()
{
var EmployeeName = "Ernestine Lamb";
object Address = "10244 Lockwood Drive";
System.Console.Write("Employee Name: ");
System.Console.WriteLine(EmployeeName);
System.Console.Write("Home Address: ");
System.Console.WriteLine(Address);
System.Console.WriteLine();
}
}
This would produce:
Employee Name: Ernestine Lamb Home Address: 10244 Lockwood Drive Press any key to continue . . .
A variable declared with object can embrace almost any value. This means that, when initializing the variable, you can use any of the types of values we have seen so far. Here are examples:
class Program
{
static void Main()
{
object propertyNumber = "293749";
object propertyType = 'S';
object stories = 3;
object bedrooms = 4;
object value = 425880;
System.Console.WriteLine("=//= Altair Realtors =//=");
System.Console.WriteLine("Properties Inventory");
System.Console.Write("Property #: ");
System.Console.WriteLine(propertyNumber);
System.Console.Write("Property Type: ");
System.Console.WriteLine(propertyType);
System.Console.Write("Stories: ");
System.Console.WriteLine(stories);
System.Console.Write("Bedrooms: ");
System.Console.WriteLine(bedrooms);
System.Console.Write("Market Value: ");
System.Console.WriteLine(value);
}
}
This would produce:
=//= Altair Realtors =//= Properties Inventory Property #: 293749 Property Type: S Stories: 3 Bedrooms: 4 Market Value: 425880 Press any key to continue . . .
Constants
Introduction
Suppose you intend to use a number over and over again. A constant is a value that never changes such as 244, "ASEC Mimosa", 39.37, or True. These are constant values you can use in your program any time. You can also declare a variable and make it a constant; that is, use it so that its value is always the same.
Creating a Constant
To create a constant, type the const keyword to its left. When declaring a constant, you must initialize it with an appropriate value. Here is an example:
const double ConversionFactor = 39.37D;
Once a constant has been created and it has been appropriately initialized, you can use its name where the desired constant would be used. Here is an example of a constant variable used various times:
class Exercise { static void Main() { const double conversionFactor = 39.37D; double meter, inch; meter = 12.52D; inch = Meter * ConversionFactor; System.Console.Write(meter); System.Console.Write("m = "); System.Console.Write(inch); System.Console.WriteLine("in\n"); meter = 12.52D; inch = Meter * ConversionFactor; System.Console.Write(meter); System.Console.Write("m = "); System.Console.Write(inch); System.Console.WriteLine("in\n"); meter = 12.52D; inch = Meter * ConversionFactor; System.Console.Write(meter); System.Console.Write("m = "); System.Console.Write(inch); System.Console.WriteLine("in\n"); } }
This would produce:
12.52m = 492.9124in 12.52m = 492.9124in 12.52m = 492.9124in
To initialize a constant variable, the value on the right side of the assignment operator "=" must be a constant or a value that the compiler can determine as constant. Instead of using a known constant, you can also assign it another variable that has already been declared as constant.
There are two main categories of constants you will use in your programs. You can create your own constants as we saw above. The C# language also provides various constants.
null: The null keyword is a constant used to indicate that a variable doesn't hold a known value
PI: PI is a constant used as the ratio of the circumference of a circle to its diameter. To use the PI constant, type it as Math.PI.
Managing Code
Introduction
The primary means of creating a program consists of writing code to. Once the code exists, you can do various things on it. For example, you select text, cut, copy or paste it, using the mouse, or a combination of the mouse and keyboard.
Accessing a Variable
The Code Editor of Microsoft Visual Studio provides many tools to assist you in managing your code:
This would display a dialog box where you can type the item and click Find. If you are using Microsoft Visual Studio and if you want to find different occurrences of a known character, symbol, word, or group of words, first select that item. Then:
In the same way, if you have a variable that is used more than once in your code and you want to see all places where that variable is used, simply click the name (and wait two seconds) and all of its occurrences would be highlighted:
To get a list of all sections where the variable is used, if you are using Microsoft Visual Studio:
This would produce a list of all sections where the variable is used and would display the list in the Find Symbol Results window:
To access a particular section where the variable is used, double-click its entry in the list.
Cutting, Copying, and Pasting Code
Normally, from your knowledge of using computers, you probably already know how to select, cut, and copy text. These two operations can be valuable to save code in Microsoft Visual Studio. This means that, if you have code you want to use in different sections, you can preserve it somewhere to access it whenever necessary.
To save code to use over and over again, first type the code in any text editor, whether in Notepad, Microsoft Word, or the Code Editor of Microsoft Visual Studio. You can use code from any document where text can be copied, including a web page. Select that code and copy it to the clipboard. To preserve it, in Microsoft Visual Studio, display the Toolbox (on the main menu, you can click VIEW -> Toolbox). Right-click an empty area on the Toolbox and click Paste.
An alternative is to select the code, whether in the Code Editor or in a text editor. Then drag it and drop it on the Toolbox. In the same way, you can add different code items to the Toolbox. After pasting or adding the code to the Toolbox, it becomes available. To use that code, drag it from the Toolbox and drop it in the section of the Code Editor where you want to use it.
Renaming a Variable
As we will see throughout our lessons, there are many names you will use in your programs. After creating a name, in some cases you will have to change it. You can find where the name is and edit it. If the name is used in many places, you can continue looking for it and modify it. There is a chance you will make a mistake. If you are writing your code using a text editor, you can use the Edit -> Replace option of the main menu to find and replace every instance of that name. You can use the same approach in the Code Editor. Unfortunately, this technique works for only one file. If your project has many files and the name is used in those files, it would be cumbersome to remember to change the name in all of them.
Microsoft Visual Studio makes it easy to find and change a name wherever it is used. Consider the following code:
To change the name of a variable, in the Code Editor:
This would display the Rename dialog box with the primary name. If you want to change it, type the new name:
If you want the studio to find and change the name inside the comments, click the Search in Comments check box. If the name is used in strings and you want to replace it, click the Search in Strings check box. When you click OK, the Preview Changes - Rename dialog box would come up. It shows the various parts where the name is used and will be replaced:
If you still want to replace, click Apply.
Accessing a Variable's Declaration
If you create a long document that has many lines of code, in a certain section you may encounter a variable but you want to find out where it was declared. If you are using Microsoft Visual Studio, to access the place where a variable was declared:
In both cases, the caret would jump to where the variable was declared.
Accessing a Line of Code by its Index
If you are using the Code Editor of Microsoft Visual Studio, if you create a long document that has many lines of code, if you want to jump to a certain line of code:
This would display a dialog box. Enter the line number and click OK or press Enter.
Primary Details on Writing Code
Type Definitition
In our lessons, we will see that there are various data types and various ways to declare things. If you are planning to use a certain type many types but think that its name is too long and/or too complicated, you can create a short or more meaningful for the type. To allow you to do this, C++ provides a keyword named typedef. The formula to use it is:
typedef data-type desired-name;
Start with the typedef keyword. Specify a known type, followed by the new name or definition you want to use. Here is an example:
typedef data-type Decimal;
After defining the type, you can use the new name as type to declare a variable. Here are examples:
typedef data-type Integer; Integer age; data-type personal; Integer pages, length, angle;
Declaring a Global Variable
Although you can declare a variable in the source file in which you want to use it, as an alternative, you can declare the variable in a header file but use that variable in another file.
Forward Declaration
Normally, before using a function, you must first define. The actual rule is that, at the time you are accessing a function, the compiler must be aware of it. In C++, you can declare a function without defining it. To do this, specify the return value of the function, its name, and its arguments if any. End that declaraction with semicolon. You can then call the function as if it had been defined already. In a later section or in another file, you can regularly defined the function.
Updating a Variable
After declaring a variable and initializing it, later in your code, if necessary, you can change the value of the variable. To do this, type the name of the variable, =, the new value, and a semicolon. Here is an example:
#include <iostream>
using namespace std;
int main()
{
int i = 5;
. . .
i = 800;
return 0;
}
INTRODUCTION TO POINTERS
Introduction
When you declare a variable, the compiler reserves an area in the computer memory for the variable. The area where the variable is positioned in the computer memory is its location. That memory area is represented with an address, just like the address or a house. You can find out what that address is. In fact, you can use or access the variable by that address.
The address of a variable is called a pointer to the variable. To indicate that you want to consider a variable based on its address, when declaring the variable, type an asterisk before its name. Here is an example:
#include <iostream>
using namespace std;
int main()
{
int *i;
return 0;
}
INTRODUCTION TO STRINGS
An Array of Characters
Introduction
INTRODUCTION TO FUNCTIONSDeclaring a Function
Introduction to Pointers to Functions
A Pointer to a Function
The primary formula to create a helper is:
A Pointer to a Method
ENUMERATIONSIntroduction to Enumerations
An enumeration is a list of constant integers where each number is represented with a name. To create an enumeration, use the following formula:
enum enumeration-name { member-1, member-2, . . . member-n};
Start with the enum keyword followed a name for the enumeration and {};. In the curly brackets, create a name for each each number you want to use. Separate those names with commas. Here is an example:
enum genders { male, female, unknown };INTRODUCTION TO CLASSES
Classes Fundamentals
Introduction
Creating a Class
To create a class, you write its code in a text-based document. You have various options. One solution is to write the class's code in a source file. In most cases, you should create your class in a header file. To do this, create the header file as we saw already. In that header file, write the necessary code.
The primary formula to create a class is:
class class-name { };
Start with the class keyword, followed by a name, and {};
INHERITANCEIntroduction
Inheritance allows you to create a new class using some functionality already available in another class. The primary formula to follow is:
class new-class-name : public existing-class-name { };
In the curly brackets, create a (the) member(s) the same way you would proceed when creating a class.
--------------------------------------------------------------A source file is a text-based document. You must create the document and save it with the extension .c. If you are using Microsoft Visual Studio to create your project, to get a source file, in the Solution Explorer, right-click the Source Files folder -> Add -> New Item... In the middle list of the New Item dialog box, select C++ File (.cpp). Accept the suggested name or change it. Then click Add.
====================================================================Practical Learning: Inserting Nodes
(['ng']);
Practical Learning: Setting the Tab Order of Controls
Practical Learning: Introducing Integers
Practical Learning: Selecting Records
Practical Learning: Deleting a Record
Practical Learning: Creating a While Loop
the method:
named
Practical Learning: Introducing Collection Iteration
Practical Learning: Introducing Date Creation
Practical Learning: Going for each Member of an Array
value:
Name |
Button |
False |
Modifiers |
Control | (Name) | DropDownStyle | |
Property #: | Label: | ||
Label | |||
City: | |||
txtCity | |||
txtState | |||
Stories: | |||
txtYearBuilt | |||
txtBedrooms | |||
0.00 | TextBox | ||
Label | |||
AcceptButton: | |
CancelButton:btnCancel | |
False | |
False | |
ShowInTaskBar:False |
Control | Text | Modifiers | Other Properties | |
dtpLastDateOccupied | ||||
txtTotalNights | 1 | Public | ||
Payment___ | ||||
Phone Use: | ||||
txtPhoneUse | 0.00 | Public | ||
txtAmountCharged | 0.00 | Public | ||
0.00 | Public | TextAlign: Right | ||
Calculate | ||||
Tax Rate: | ||||
txtTaxRate | 7.70 | Public | ||
txtTaxAmount | 0.00 | Public | ||
Amount Paid: | ||||
txtTotalAmountPaid | 0.00 | Public | TextAlign: Right | |
_______________ | Label | |||
Receipt #: | ||||
Label | Label | |||
btnOK | OK | DialogResult: OK | ||
btnCancel | Cancel | TextBox | Button |
(Name) | Width |
Last Name | 65 |
colPhoneNumber | Phone # |
Emergency Name | 100 |
Emergency Phone | 100 |
Control | (Name) | Text | |
lvwCustomers | View: Details |
||
btnNewCustomer | |||
btnClose | Close |
|
(Name) | Text | Width |
colEmployeeNumber | Employee # | 70 |
colFirstName | First Name | 80 |
colLastName | Last Name | 80 |
colTitle | Title |
(Name) | Text | Other Properties | |
lvwEmployees | View: Details |
||
btnNewEmployee | |||
btnClose |
TextAlign | Width | ListView | Button |
colRoomNumber | Room # | ||
colRoomType | Room Type | 100 | |
colBedType | Bed Type | 80 | |
colRate | Rate | ||
colAvailable | Available? | Center | 65 |
Control | (Name) | Text | Other Properties | |
ListView | lvwRooms | View: Details |
||
Button | btnNewRoom | New Room... | ||
Button | btnClose | Close |
Text | TextAlign | Width | |
colOccupancyNumber | Occupancy # | 80 | |
Date Occupied | 150 | ||
Processed By | 140 | ||
Processed For | 140 | ||
Room Occupied | 180 | ||
Rate Applied | Right | 80 | |
Phone Use | Right | 65 |
FullRowSelect: TrueGridLines: True View: Details |
|
(Name) | Text | TextAlign |
Processed By | 140 | |
130 | ||
Processed For | 140 | |
First Day Occupied | 140 | |
Last Day Occupied | 140 | |
Total Nights | Right | 70 |
colAmountCharged | Amt Charged | Right |
colPhoneUse | Phone Use | Right |
colSubTotal | Right | |
colTaxRate | Right | |
Tax Amt | Right | 55 |
Amt Paid | Right |
Control(Name) | Text | Other Properties |
FullRowSelect: TrueGridLines: True View: Details |
||
btnNewPayment | ||
btnClose | Close |
Editor | (Name) | Text |
btnCustomers | Button | |
btnOcupancies | Button | |
btnRooms | Rooms... | |
btnPayments | Payments... | |
btnEmployees | ButtonEmployees... | |
btnClose |
Form | |
FormBorderStyle:FixedDialog | |
Ceil Inn - Employee Editor | |
CenterScreen | |
btnOK | |
CancelButton: | |
False | |
MinimizeBox: | |
ShowInTaskBar: |
(Name) | Text | Modifiers | Other Properties |
Employee Number: | Label | ||
Public | TextBox | ||
Label | |||
txtFirstName | Public | ||
Last Name: | >Label | ||
txtLastName | |||
Label | |||
txtTitle | |||
btnOK | OK | ||
btnCancel |
Introduction to the Attributes of a File
Control | (Name) | Text | Modifiers |
Account Number: | |||
txtAccountNumber | Public | ||
First Name: | |||
txtFirstName | TextBoxLabel | ||
Last Name: | |||
txtLastName | Public | TextBox | |
Phone Number: | |||
txtPhoneNumber | Public | ||
Emergency Name: | Label | ||
txtEmergencyName | Public | ||
Emergency Phone: | |||
txtEmergencyPhone | |||
btnOK | OK | ||
btnCancel | DialogResult: Cancel |
FixedDialog |
Ceil Inn - Customer Editor |
StartPosition: |
btnOK |
btnCancel |
False |
MinimizeBox: |
False |
Introduction
parameter.
When
s(es).
The type.
This event is carried by the class
Like is a
The
for.
rreferred to as a wheel.
.
To implement this event, a argument is passed to the
To declare a variable that can hold one character, a letter, or a symbol, use either the
The. Here is an example:
This would produce:
ollows:
Like
Introduction
To support drag n' drop operations, the .NET Framework provides various events through the .
The an enumeration.
the
based on the
same value. Here is an example:
To . Its syntax is:
Control's Construction and Destruction
. Here is an example:
is:
. Here is an example:
In
a valid value. Here is an example:
The
Accessing the Members of an Array
Using a Non-Integer-Based Index
an example of a float array:
This would produce:
Introduction to the .NET Framework
, you can add is
.
i. Here is an example:
he variable. Here is an example:You can also call this method from a variable that accesses the
Practical Learning: Setting the Title of a Form
The Width of a Form
the
Practical Learning: Introducing File Information
Delegates
Introduction
delegate.s.
Practical Learning: Creating a Stream
Practical Learning: Using a Local Object
A Helping Static Class
Introduction
class.
, , virtual, or overrides.
Practical Learning: Adding a Property to an Interface
Here is an example:
method.
Practical Learning: Adding a Method to an Interface
IPolygon
Practical Learning: Passing an Interface As Argument
Page and IsPostcode in an ASP.NET MVC application, the .NET Framework provides a clas named HtmlHelper. This class is directly derived from Object reviewed for the WebPage class.To let you add a webcontrol to a form, the HtmlHelper class is extended with various overloaded methods for different HTML objects. The methods are TextBox() for a text box, CheckBox() for a check box, RadioButton() for a radio button. The simplest version of each method takes only one argument. For example, the syntax for a simple text box is:INPUT control of type SUBMIT. Here is an example:
Second, create a Razor code section that contains a contional statement that checks the value of an IsPost property. Here is an example:
Practical Learning: Creating an Interface
classes.Instead of names of variables, fields or properties, you can call other functions for the value(s) of the argument(s) after the first argument.
above. method.example:
X5. names as follows:When working on a switch null. Here is an example:
nullis null or not. To let you get this information, the C# language provides the is operator. To use it, create a conditional operator using the following formula:
r. Here is an example:
This would produce:
This would produce:
Still, if you want, you display the value of a member a for loop re-initialize the array by allocating new memory to it.
This would produce:
This would produce:
This would produce:
Introduction to Controllers
So .
Creating a Form in a View
Beginning a Form
s of statement.
Checking for Nullity
Comparing an Object to Nullity
ight operand. Here is an example:
mparing two objects. This operation can be performed =
The Null-Conditional Operator
We already saw how to find out whether an object of such a class is currently valid. Here is an example:
. Here is an example:
Here is another version of the code:
The Null Coalescing Operator
. Here is an example:
beds = ?? 0;
House class:
object1 is object2
A Null Object
A variable that has been declared for a class but that has not yet received values for its properties in referred to as a null object.
. Here are examples:
A Null Field
k to it. Here are examples:
The .
This would produce:
This would produce:
. Here is an example:
Introduction to Nullity
The Nullity of a Variable
variable.
value.
A Null Value for a Primitive Type
estion mark to it.
Imagine you want to create an object from an interface or a class:
perties in referred to as a null object.
. Here are examples:
A Null Field
Here is an example:
This would produce:
This would produce:
A regular formula to use a read-write property is:
[index] = value; . . . [] = Value_n;
. Here is an example:
backslashes.
In Lesson 2 manage escape sequences . Here are examples:
path.
Introduction to the Label Control
Overview of Labels
. Here is an example:
method. Here is an example:
method.
l. Here are example:
. In the parentheses, pass the name of the control.
property and assign the desired integer to it.
. Toit.
Practical Learning: Specifying the Top Position of a Control
The Text of a Control
property.
Practical Learning: Setting the Caption of a Label
The Width of a Control
.
Practical Learning: Specifying the Width of a Control
)
can be anything. By convention, it is named e and yn action is delimited by curly brackets. Here is an example:
Practical Learning: Introducing Events
Practical Learning: Introducing Events
Converting a Value to a Natural Number
t . Here is an example:
Converting a Value to a Decimal Format
The basic formula to convert text to a decimal number is:The description is the same as for the integer.
This would produce:
This would produce:
A Delegate That Takes One of More Arguments
returns a value):
delegate double Addition(double x, double y);
Here is an example:
. Here is an example:
)
the delegate.
A delegate. Here is an example:
After declarimplements the needed behavior of that delegate. Here is an example:
You. Here is an example:
.
value to the constant.
as follows:
double data type. This version of the program would produce:
: Here are examples:
This version of the program would produce:
F
the.
Location field:The purpose of this program is to get the division of 560 by 672. This would produce:
Checking for Nullity
Comparing an Object to Nullity
. Here is an example:
On the other hand, to find out whether an object is not null, you can use the != operator with the null keyword as the right operand. Here is an example:
Checking Whether Two Objects Use the Same Reference
When you are dealing with various types of objects in a section of code, you may be interested in comparing two objects. This operation can be performed using the is operator. The formula to use it is:
= is
false.. Here is an example:
. Here is an example:
. If it doesn't, then the member on its right is accessed and the operation that must be performed proceeds.This
Checking Whether an Object IS Null
is operator. To use it, create a conditional operator using the following formula:
variable is null) statement(s);
. Here is an example:
StreamReader object, make sure you close it.
FileInfo class is equipped with a method named Open the FileInfo class is equipped with a method named OpenText. Its syntax is:FileInfo object. Here is an example:
In the same way, you can have other methods that call that method. Here are examples:
)
)
Getting this Parent
A Re-Introduction to Windows Controls
A Windows Control as a Class
As menti
Introduction to the Properties of a Class
is:
options data-type property-name { get; set; }
Throughout our lessons, we will find out what the starting options are (for now, let's ignore that). By the way, unlike some languages, C# doesn't use property as a keyword.
example of a property created in a class:
Practical Learning: Returning a Value From Main()
Size except that its members float
if (fleMembers.Exists == true)
With.
Here is an example of what this would produce:
Bottom. Based on this, a rectangle can be illustrated as follows:
someFile.Extension
This would produce:
ToString()
Point value Size value Rectangle a Point
Besides the Rectangle structure, the System.Drawing namespace provides the RectangleF structure that uses the same definition as Rectangle, except that it is defined with float values instead of integers.
The Bounds. This property is of type Rectangle represented by the property. Therefore, at any time, to get the location and the size of a control, you can call its Bounds property Rectangle value.
Techniques of Visually Resizing a Control
Introduction
control.
ontrol:
To narrow a control:
To heighten a control:
To shrink a control:
We know that we can use the square brackets to access each member of an array, one item at a time. That technique allows you to access one, a few, or each member. If you plan to access all members of the array instead of just one or a few, you can use the for loop. The formula to follow is:
for(data-type initializer; end-of-range; increment) statement(s);
In this formula, the for keyword, the parentheses, and the semi-colons are required. The data-type is used to specify how you will count the members of the array.The Initializer specifies how you would indicate the starting point of the count. As seen in Lesson 22, this initialization could use an initialized int-based variable.The EndOfRange conditional operation (<, <=, >, >=, or !=) with the number of members of the array minus 1.The Increment factor specifies how you would move from one index to the next.
numbers[i]
d produce (throw) foran error (called an exception). Here is an example:
Practical Learning: Using a for Loop
Looping Through an Array of Items
Going For Each Item in the Array
You can use the foreach operator to visit each member of the array. In this case, you don't need the GetValue() method. Here is an example:
Practical Learning: Visiging Each Object of an Arrray
Practical Learning: Breaking the Flow of a Loop
Selecting a Value From a List
Introduction
for or a foreach loop. Here is an example that produces the first 4 values of the array:
if (i < 4)
This would produce:
This would produce:
SizeNameon select:
Result: All base control:
Result: All controls,trol:
Result: (AvgHeight). width (AvgWidth
The Content Alignment of a Control
the TextAlign property. To specify the alignment of text during design, access the Properties window for a control and use the TextAlign field:
ContentAlignment, which is an enumeration. The members and result of this enumeration are:
To programmatically specify the text alignment of a control, access its TextAlign property and assign it the desired member of the ContentAlignment enumeration. Here is an example:
Anchor property:
Bottom
Left
In the same way, you can combine AnchorStyles values to glue one or more corners of a control to its parent when the parent is resized:
This property is managed through the
Bottom
Fill
Left: The control will be attached to the left border of its parent:
None: The control will be kept where it was positioned on the parent:
Right: The control will be attached to the right border of its parent:
Top: The control will be attached to the top border of its parent:
Aesthetic Aspects of a Control
Background Color
Control the BackColor field of the Properties window:
As called Color.
Practical Learning: Changing the Background Color of a Control
BackgroundImage
the following:
BorderStyle property, which is based on BorderStyle enumerator. Its members are:
BorderStyle. Here is an example:
False.
If a control has the
Practical Learning: Setting the Tab Order of Controls
Controls property.
False or set its parent’s visible property to False. Equivalently, at run time, to hide a control, assign a FalseVisible property or its parent’s Visible property. Keep in mind that when a parent gets hidden, it also hides its children. On the other hand, a parent can be made visible but hide one or some of its children.
To programmatically check whether a control is visible at one time, apply a conditional statement (if or while) to its Visible property and check whether its value is true or false.
By default, after adding a control to a form, it is enabled and its Enabled property in the Properties window is set to True. An enabled control displays its text or other characteristics in their normal settings. If you want to disable a control, set its Enabled property to False. In the following picture, a text box and a button are disabled:
where.
rectangle:
Focus method. Its syntax is:
its
:
After GetTopLevel() s:
Practical Learning: Introducing the Characteristics of Windows Controls
The Content Alignment of a Text Box
field. It is based on an enumeration named HorizontalAlignment. When you click OK, s .
Practical Learning: Aligning the Content of a Text Box
This would produce:
the C#'s .
. Here is an example:
Welcome to our website. Here is you will find the latest in fashion and body accessories.
. Here is an example:
pr
Introduction to Parameters and Arguments
Introduction to the Parameters of a Helper
string:
. Here is an example:
In the body of the helper, you can also ignore the parameter.
Here is an example:
. Here is an example:
string roofMaterial = "Asphalt Shingles; roofMaterial
. Here is an example:
want.
The Scope and Lifetime of a Variable
Introduction
global scope.
. Here is an example:
The Scope and Lifetime of an Object
. Here is an example:
. Here are examples:
You can also use Here is an example:
. Here is an example:
This would produce:
. Here is an example:
Practical Learning: Creating a Helper
Practical Learning: Creating an Interface
Practical Learning: Using a Local Object
Practical Learning: Adding a Property to an Interface
In
object.
Practical Learning: Returning an Interface
Implementing Many Interfaces
. Here is an example:
Control | Name | Text |
Label | Order Total: | |
txtOrderTotal | 0.00 | |
Label | Amount Tendered: | |
txtAmountTendered | 0.00 | |
Button | btnCalculate | Calculate |
Label | Difference: | |
TextBox | txtDifference | 0.00 |
Button | btnClose | Close |
Practical Learning: Introducing Integers
Control | Name | Text | Additional Properties |
GroupBox | grpIceCream | ||
Label | Order Date: | ||
TextBox | txtOrderDate | ||
Label | |||
TextBox | |||
Label | |||
TextBox | txtFlavor | ||
Label | |||
TextBox | txtContainer | ||
Label | Ingredient: | ||
TextBox | txtIngredient | ||
Label | Scoops: | ||
TextBox | txtScoops | 1 | TextAlign: Right |
Label | Order Total: | ||
TextBox | txtOrderTotal | 0.00 | TextAlign: Right |
Button | btnCalculate | Calculate | |
Button | btnNewOrder | New Order | |
Button | btnMoneyChange | Money Change | |
Button | btnClose | Close |
private
Amount: | ||
Label | ||
Label | ||
Part 1 Receives: | ||
txtPart1 | TextAlign: Right | |
txtPart2 | ||
Button | btnClose | Close |
Control | Name | Text | Additional Properties |
Label | Side: | ||
TextBox | txtSide | 0.00 | TextAlign: Right |
Button | btnCalculate | Calculate | |
Label | Edges | ||
TextBox | txtEdges | TextAlign: Right | |
Label | Internal Angle: | ||
TextBox | txtInternalAngle | TextAlign: Right | |
Label | Perimeter: | ||
TextBox | txtPerimeter | TextAlign: Right | |
Label | Area: | ||
TextBox | txtArea | TextAlign: Right | |
Label | In-Radius: | ||
TextBox | txtInradius | TextAlign: Right | |
Label | Circumradius | ||
TextBox | txtCircumradius | TextAlign: Right | |
Button | btnClose | Close |
Practical Learning: Introducing Loops
Practical Learning: Creating a While Loop
int
Presenting a Character
public static void Write(char value);
This would produce:
This would produce:
This would produce:
If you want to move to the next line after displaying the character, the Console class provides the following version of the WriteLine() method:
);
Control | (Name) | Text | |
Label | txtNewPassword | ||
TextBox | txtCharacters | ||
Label | Characters |
Here are examples of calling this method:
This would produce:
Practical Learning: Overloading an Indexer
Main().
T
members.GetValue(List , Element ));
the following code written in a file saved as Exercise.cs:
To execute the application, at the Command Prompt and after Changing to the irectory that contains the file, you would typeand press Enter. To execute the program, you would type the name Exercise and press Enter. The program would then prompt you for the information it needs.
The above program produces:
csc to the Main().
.
Here is an example:
Here is an example:
This would produce:
To execute the program, you would type Exercise
CommandLine.
than void. Here is an example:
return
After. Here is an example:
Collection<T>
This would be done as follows:
This would produce:
. Here is an example:
Practical Learning: Introducing Collection Iteration
This would produce:
Practical Learning: Enumerating a Collection
Unit Code | Aprt # | Bedrooms | Bathrooms | Monthly Rate | ||
399475 | 101 | 2 | 2 | 1150 | 650 | Available |
508293 | 102 | 1 | 1 | 950 | 500 | |
928364 | 104 | 3 | 2 | 1350 | 850 | Available |
297297 | 105 | 2 | 1 | 1150 | 550 | Available |
492739 | 106 | 3 | 2 | 1350 | 850 | Available |
692797 | 107 | 3 | 2 | 1285 | 850 | Not Ready |
829475 | 108 | 1 | 1 | 885 | 500Available | |
139749 | 109 | 2 | 2 | 1150 | 650 | Available |
369294 | 110 | 1 | 1 | 895 | 500 | |
502084 | 111 | 2 | 2 | 1145 | 650 | Available |
112 | 2 | 1 | 1085 | 600 | Available | |
292739 | 201 | 2 | 1 | 1185 | 650 | Available |
496055 | 202 | 1 | 1 | 895 | 500 | Available |
939595 | 203 | 1 | 1 | 925 | 500 | Available |
384068 | 204 | 3 | 2 | 1250 | 850 | Available |
824850 | 205 | 2 | 1 | 1100 | 600 | Available |
620485 | 206 | 3 | 2 | 1300 | 850 | Available |
294940 | 207 | 3 | 2 | 1350 | 850 | Available |
602048 | 208 | 1 | 1 | 920 | 500 | Available |
829479 | 209 | 2 | 2 | 1150 | 650 | |
280484 | 210 | 1 | 1 | 895 | 500 | Available |
602408 | 211 | 2 | 2 | 1175 | 650 | Available |
384086 | 212 | 2 | 1 | 1075 | 600 | Available |
397493 | 301 | 2 | 2 | 1175 | 650 | Available |
625941 | 302 | 1 | 1 | 950 | 500 | Available |
404950 | 303 | 1 | 1 | 925 | 500 | Available |
304806 | 304 | 3 | 2 | 1250 | 850 | Available |
844850 | 305 | 2 | 1 | 1100 | 600 | Needs Repair |
596305 | 306 | 3 | 2 | 1300 | 850 | Available |
138408 | 307 | 3 | 2 | 1350 | 850 | Available |
305860 | 308 | 1 | 1 | 920 | 500 | Available |
847584 | 309 | 2 | 2 | 1150 | 650 | Available |
746959 | 310 | 1 | 1 | 935 | 500 | Available |
359405 | 311 | 2 | 2 | 1175 | 650 | Available |
308505 | 312 | 2 | 1 | 1075 | 600 | Available |
Practical Learning: Combining Various Disjunctions
na; } mg; } Al")al; } Si")
He")he; } Li")li; } Be")be; } B") b; } C") c; } N") n; } o") o; } F") f; } Ne")ne; } Na")na; } Mg")mg; }
Practical Learning: Combining Various Disjunctions
Looping Each Object
square brackets.
Practical Learning: Going for each Member of an Array
Introduction to Collection-Based Controls
The Checked List Box
. Here is an example:
. Here is an example:
This would produce:
You can also add an array of items by calling the AddRange() the Insert()
ThreeDCheckBoxes property from its False default to a True value:
Application: Introducing Streaming
Introduction to the Attributes of a File
file.
HorizontalAlignment. When you click OK, s . class is equipped with a method named ReadLine(). StreamReader object, make sure you close it.
Introduction
File streaming consists of performing one of the routine operations on a file, such as creating it or opening it. This basic operation can be performed using a class called FileStream. You can use a FileStream object to get a stream ready for processing. As one of the most complete classes of file processing of the .NET Framework, FileStream is equipped with all necessary properties and methods. To use it, you must first declare a variable of it. The class is equipped with nine constructors.One of the constructors of the FileStream class has the following syntax:
public FileStream(string path, FileMode mode);
This constructor takes as its first argument the name of the file or its path. The second argument specifies the type of operation to perform on the file. Here is an example:
Application: Creating a Stream
No Change
The Database Owner
named databases (actually, it's a view). When you create a database, its name is entered in the databases object using the same name you gave it. dbo. This account is automatically granted various permissions on the databases of the server. Because the dbo account has default access to all databases, to refer to an object of a database, you can qualify it by typing dbo, followed by the period operator, followed by the name of the object.
CREATE SCHEMA schema_name_clause [ <schema_element[ ...n ] ]
In this case, start with the CREATE SCHEMA expression and add a name to it. Here is an example:
CREATE SCHEMA Accessories;
GO
As an option, you can start the name with [ and end it with ], as in:
[
named dbo. This is probably the most common schema you will use. In fact, if you don't create a schema in a database, the dbo schema is the default and you can apply it to any object in your database.
Introduction to Tables
Introduction
programmatically in C#.
Visually Creating a Table Locally
To visually create a table, in the Object Explorer of Microsoft SQL Server Management Studio, expand the database. Right-click the Tables node -> New -> Table... To visually create a tableclick Server Explorer, expand the connection, right-click Tables and click Add New Table. A new window that will call the Table window will display. You can then add the necessary options.
button
Practical Learning: Introducing Databases
Programmatically Creating a Table
To create a table with SQL code, the DDL formula to start is as follows:
CREATE TABLE table-name;
The CREATE TABLE expression is required. The table-name.
Introduction to the Columns of a Table
Overview
section.
We saw that the primary formula to create a table was:
CREATE TABLE table-name
This formula is followed by parentheses:
CREATE TABLE table-name()
A column or the list of columns starts with an opening parenthesis "(". The list ends with a closing parenthesis ")".
CREATE TABLE [SchemaName.]Country(Column1, Column2, Column3)
as follows:
column_2, column_n);
create a column is:
column-name data-type options
Each column must have a name. The name of a column:
As an alternative, you can include the name of the column between [ and ].The second very important piece of information of a culumn is the type of its values.
Referring to a Column
To refer to a column in an expression, you have various options:
Using the Alias Name of a Table
empl.LastName be Employee empl. You can also type AS between the name of the table and its alias. An example is Employee AS empl.
Introduction to Data Entry
A table is an object that holds the data of a database. You can add records to a table visually or using code. To open a table for visual data entry:
Text-Based Columns
The values of a column can consist of a character of any kind of alphabetical symbol, readable or not. To let you create a column where the records will hold a character, the SQL provides the CHAR data type to it. As an alternative, you can use the VARCHAR data type. If you anticipate that the values of the column may use ASCII characters or Unicode (or international characters, or characters other than US English), precede the data type with N, as NCHAR or NVARCHAR. Here are examples:
Also, the name of a column can be included in square brackets.
Remember that the SQL is not case-sensitive. Therefore, you can specify the data type in lowercase, as in char or nchar.
String-Based Colummns
options.
The Maximum Length of a String-Based Record
NCHAR.
CHAR, the VARCHAR, the NCHAR, or the NVARCHAR.
Practical Learning: Creating a Table
Long Text-Based Columns
varchar() or nvarchar() and specify the length using the max keyword. Here is an example:
In this case, varchar(max) or nvarchar(max) text (and ntext for Unicode) used for long text. Here are examples:
Practical Learning: Creating a Column for Long Text
Regular Integers
INTEGER data type.
TINYINT
The SMALLINT data type follows the same rules and principles as the C#'s short data type to store numbers that range between -32,768 and 32,767.
Long Integers
To create a column that can hold large numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, apply the BIGINT data type to it. This type follows the same rules and principles as the C#'s long data type.
Practical Learning: Creating Integer-Based Columnt
If you anticipate that some entries would be different than others, then use the alternative varbinary data type. The varbinary type also is used for hexadecimal numbers but allows dissimilar entries, as long as all entries are hexadecimals.
Decimal Number-Based Columns
Introduction
numeric or decimal.
The Precision of a Decimal Number
int and float and real), the precision is fixed by the database and you can just accept the value set by the Microsoft SQL Server interpreter. For a decimal number (decimal or numeric data types), Microsoft SQL Server allows you to specify the amount of precision you want. The value must be an integer between 1 and 38.
The Scale of a Decimal Number
numeric and decimal the decimal or numeric data type, you can specify the amount of scale you want. The value must be an integer between 0 and 18.
Currency Values
If a column will hold monetary values, you can set its data type as MONEY or SMALLMONEY. A column with a money data type can hold positive or negative values from -922,337,203,685,477.5808 to +922,337,203,685,477.5807. While the money data type can be used for a column that would hold large quantities of currency values, the smallmoney data type can be applied for a column whose value cannot be lower than -214,748.3648 nor higher than 214,748.3647.
The precision and scale of a money or smallmoney column are fixed by Microsoft SQL Server. The scale is fixed to 4.
Date and Time Values
A Date-Based Column
DATE data type. Here is an example:
A Date/Time Column
DATETIME2the datetime or the datetime2 data type.
Boolean-Based Columns
Alternative Bits
. Another option is to use a string-based type.
User-Defined Types
Creating a User-Defined Type
CREATE TYPE AliasName FROM BaseType
Start with the CREATE TYPE expression, followed by the desired name for the new type. After the FROM keyword, type an existing Transact-SQL data type. Here is an example:
Introduction to Built-Functions
Overview
Parsing an Expression or Value
Parsing.
To assist you with parsing, Transact-SQL provides a function named PARSE. Its syntax is:
PARSE ( string_value AS data_type [ USING culture ] )
string_value rules of the data_type argument data_type as int.
If the argument may include international characters or formats (Unicode), you should indicate the language, called a culture, that the argument follows.
If the PARSE() function is not able to determine the type or if the value of the argument doesn't follow the rule of the data_type, this function produces (throws) an error. As an alternative to PARSE(), Transact-SQL provides the TRY_PARSE() function. Its syntax is:
TRY_PARSE ( string_value AS data_type [ USING culture ] )
As you can see, this function uses the same argument as PARSE. The difference is that, while PARSE() produces an error if the parsing operation fails, TRY_PARSE produces NULL (if the parsing operation fails). This means that, in most cases, you should prefer TRY_PARSE() instead of PARSE().
Casting a Value
In
either the Convert class or a Parse() the CAST() or the CONVERT() function. The syntax of the CAST() function is:
CAST(Expression AS DataType)
The Expression is the value that needs to be cast. The DataType factor is the type of value you want to convert the Expression to. The DataType can be one of those we reviewed in Lesson 23.
If the CAST() function is not able to cast the expression (if it fails), it produces (throws) an error. As an alternative to CAST(), Transact-SQL provides a function named TRY_CAST. Its syntax is:
data_type [ ( length ) ] )
TRY_CAST() fails, it returns NULLTRY_CAST() instead of CAST.
Here is an example:
N2W2.18'; SET @StrHours = N'38.50';
Converting a Value
Like CAST(), the CONVERT() function is used to convert a value. Unlike CAST(), CONVERT can be used to convert a value from its original type into a non-similar type. For example, you can use CONVERT to cast a number into a string and vice-versa.
The syntax of the CONVERT() function is:
[ ( length ) ] , Expression [ , style ])
varchar, nvarchar, char, nchar) or a binary type, you should specify the number of allowed characters in the data types own parentheses, as the length argument.
CAST() function, the Expression is the value that needs to be converted.
If the conversion is performed on a date or time value, the style argument is a number that indicates how that conversion must proceed.
If the CONVERT() function is not able to perform its operation, it produces an error.
Because of some difficulties that can result from conversion, Transact-SQL provides a function named TRY_CONVERT. Its syntax is:
TRY_CONVERT ( data_type [ ( length ) ], expression [, style ] )
The arguments are the same used in the CONVERT() function. The difference is that if the TRY_CONVERT() function fails, it returns NULL instead of producing (throwing) an error.
Here is an example:
PRINT N'Square Characteristics'; PRINT N'-----------------------'; PRINT N'Side = ' PRINT N'Perimeter = ' PRINT N'Area = ' GO
Transact-SQL Macros and Metadata Functions
Introduction to Macros
Checking the Existence of a Record
EXISTS. Its syntax is:
BIT EXISTS(SELECT Something)
This macro takes one argument. The argument must be a SELECT statement that would be used to get the value whose existence would be checked. For example, we know a system database named databases that contains a record of all databases stored on your server. You can use the EXISTS() macro to check the existence of a certain database.
Introduction to Metadata Functions
server.
OBJECT_ID('[ database_name . [ schema_name ] . | schema_name . ] object_name' [ ,'object_type' ]);
object_name, is the name of an object such as a table. Here is an example:
OBJECT_ID(N'Employees'),
N'LastName',
N'precision'
dbo
OBJECT_ID() object_name argument. It is passed as one or two letters depending on the object. For a table, the argument is passed as 'U'.
The Identifier of a Database
DB_ID() function. Its syntax is:
DB_ID ( [ 'database_name' ] ) RETURNS int;
. Here is an example:
. Here is an example:error).
. Here is an example:
arguments:
The function would produce | |
1 | master |
2 | tempdb |
3 | model |
4 | msdb |
5 | ReportServer |
6 |
DB_ID and pass it as argument. Here is an example:
SELECT DB_NAME(DB_ID(N'KoloBank')) AS [Kolo Bank]; GO
SUSER_ID or the SUSER_SID function. Their syntaxes are:
SUSER_NAME or the SUSER_SNAME function. Their syntaxes are:
The Name of the Computer
HOST_NAME() function. Its syntax is:
Fundamentals of String-Based Functions
Introduction
string.
LEN() function. Its syntax is:
int LEN(String)
example:
Concatenating Two Strings
operator '+'. Here are examples:
N'Jerome '; SET @LastName = N'Ansfield'; SET @FullName = @FirstName + @LastName; SET @CompleteName = N'Anne ' + N'Sanders'; SELECT N'Jeffrey ' + N'Erschbamer'; SELECT @FullName [Full Name]; SELECT @CompleteName [Complete Name]; GO
In the same way, you can concatenate various strings by using the addition operator between them. Here are examples:
SET @FirstName = N'Jerome'; SET @LastName = N'Ansfield'; SET @FullName = @LastName + N', ' + @FirstName; SET @CompleteName = N'Anne' + N' ' + N'Juliette' + N' ' + N'Sanders'; SELECT @FullName [Full Name]; SELECT @CompleteName [Complete Name]; SELECT N'Jeffrey' + N' ' + N'Anselme' + N' ' + N'Erschbamer'; GO
Transact-SQL provides a function that performs string concatenation. It is named CONCAT and its syntax is:
string, string stringstring
string as char or one of its variants (nchar, char(n), varchar, nvarchar, or nvarchar(n), or nvarchar(max).
strings:
SET @FirstName = N'Jerome '; SET @LastName = N'Ansfield'; SET @FullName = ; SET @CompleteName = CONCAT(N'Anne ', N'Sanders'); SELECT CONCAT(N'Jeffrey ', N'Erschbamer')
arguments:
N'Jerome'; N'Ansfield'; CONCAT(@LastName, N', ', @FirstName); CONCAT(N'Anne', N' ', N'Juliette', N' ', N'Sanders'); CONCAT(N'Jeffrey', N' ', N'Anselme', N' ', N'Erschbamer');
Strings and Type Conversion
FORMAT()
value, nvarchar format [, nvarchar culture ] ) RETURNS nvarchar
The FORMAT()variances.
The second argument in mind:
. Here is an example:
SET SELECT @YearlySalary AS "Yearly Salary", @FiscalBudget AS "Company Budget"; GO
FORMAT() function. Pass the value as the second argument and pass the second argument as:
FORMAT(@HourlySalary, N'D') AS "Hourly Salary", FORMAT(@Distance, N'D') AS Distance; GO
DECLARE @HourlySalary int, @UnitPrice decimal(8, 4), @FiscalBudget bigint; SET @HourlySalary = 28.65; SET @UnitPrice = 349.95; SET @FiscalBudget = 12640685; SELECT FORMAT(@HourlySalary, N'E') AS "Hourly Salary", FORMAT(@UnitPrice, N'e') [Unit Price], FORMAT(@FiscalBudget, N'E') AS N'Company Budget'; GO
N'C') AS "Hourly Salary", FORMAT(@UnitPrice, N'C') [Unit Price], FORMAT(@FiscalBudget, N'c') AS N'Company Budget'; GO
FORMAT()argument, culture. Here are examples:
Converting From Integer to ASCII
ASCII(). Its syntax is:
int ASCII(String)
. Here is an example:
Converting From ASCII to Integer
CHAR() function. Its syntax is:
CHAR(int value) RETURNS char;
that number.
don't LOWER() function. Its syntax is:
LOWER(String) RETURNS varchar;
"as is". After conversion, the LOWER(). Here is an example:
DECLARE @FIFA nvarchar(120)
SET @FIFA = N'Fédération Internationale de Football Association'
SELECT @FIFA AS FIFA
SELECT LOWER(@FIFA) AS Converted
Sub-Strings
The Starting Characters of a String
A sub-string is a section gotten from a string. The idea is to isolate one or a group of characters for any necessary reason.
A left sub-string is one or a group of characters retrieved from the left side of a known string. To get the left sub-string of a string, you can use the LEFT() function. Its syntax is:
LEFT(String, NumberOfCharacters) RETURNS varchar
LEFT() NumberOfCharacters the String.
The Ending Characters of a String
RIGHT() function. Its syntax is:
RIGHT(String, NumberOfCharacters) RETURNS varchar;
Replacing Occurrences in a String
REPLACE() is:
String, FindString, ReplaceWith) RETURNS varchar;
or
String, FindString, ReplaceWith) RETURNS binary;
FindString the String argument.
If the FindString character or sub-string is found in the String,
then it is replaced with the value of the last argument, ReplaceWith.
Table Maintenance
Tables Review
sp_help type sp_help and click the Execute button .
The Schema of a Table
To specify the schema of a table when creating a table using code, precede its name with the name of the schema followed by a period. The formula to use is:
CREATE TABLE SchemaName.TableName....
An example would be:
CREATE SCHEMA Registration;
GO
CREATE TABLE .
If you don't specify a particular schema, the default dbo schema takes ownership of the table.
Renaming a Table
If you find out that the name of a table is not appropriate, you can change it. To change the name of a table with code, execute sp_rename, followed by the current name of the table, a comma, and the new desired name of the table. The formula to use is:
sp_rename ExistingTableName, TableNewName;
The names of tables should be included in single-quotes. Here is an example:
In this case, the SQL interpreter would look for a table named StaffMembers in the current or selected database. If it finds it, it would rename it Employees. If the table does not exist, you would receive an error.
Deleting a Table
If you have an undesired table in a database, you can remove it. To visually delete a table, in the Server Explorer, right-click the table and click Delete
You will receive a warning giving you a chance to confirm your intentions. If you still want to remove the table, click OK. To delete a table using SQL, use the following formula:
DROP TABLE table-name
The DROP TABLE expression is required and it is followed by the name of the undesired table.
Referring to a Table
To refer to a table in an expression, if you didn't create the table in a particular schema:
If you add created the name in a specific schema:
Columns Maintenance
Introduction
etc.
The Collation of a Column
Collation property.
COLLATE, followed by the desired collation code. Here is an example:
Modifying a Column
When using this statement, the ALTER TABLE.
ALTER TABLE table-name ADD ColumnName Properties
The column-name factor is required. In fact, on the right side of the is an example:
ALTER TABLE Customers
ADD EmaillAddress varchar(100);
GO
varchar
Renaming a Column
sp_rename using the following formula:
sp_rename 'table-name.column-name', 'NewColumnName',
The sp_rename factor and the 'COLUMN' string are required. The table-name factor is the name of the table that the column belongs to. The column-name is the current name of the column. The NewColumnName is the desired name you want to give to the column. Here is an example:
sp_rename 'StaffMembers.FullName', 'EmployeeName', 'COLUMN';;
GO
.
Deleting a Column
formula:
ALTER TABLE table-name DROP COLUMN column-name
On the right side of the ALTER TABLE expression, type the name of the table. On the right side of the DROP COLUMN expression, enter the name of the undesired column. Here is an example:
ALTER TABLE Customers DROP Column DateIssued;; GO
Introduction to Data Entry
value.
Practical Learning: Introducing Records
Visual Data Entry on Bit Values
When creating a record for a column that uses a BIT data type, in the Query window, you can specify the value as true (case-insensitive), false (case-insensitive), 1 (which is the same as True), or 0 (which is the same as False). No other string or number is allowed.
Data Entry for an Integral Column
If the column is a natural numeric type (INT, INTEGER, BIGINT, SMALLINT, or TINYINT), simply provide a valid natural number for it.
When providing the value of a column that is of binary type, type its as a normal integer.
Data Entry for Floating-Point Numbers
If you create a column that would use decimal numbers (FLOAT, REAL, DECIMAL, or NUMERIC), when specifying the value of the column, you have two options. If the value doesn't need precision, you can provide it as if it were a natural number. If the value needs or uses a precision, include the decimal separator (the period for US English).
Monetary Values and Data Entry
digits.
Data Entry for Characters and Strings
If the data type of a column is a character (CHAR or NCHAR), a string (CHAR or NCHAR), simply type its value. If you apply the char data type to a column, it can hold a maximum of 8000 characters.
Data Entry for Date-Based Columns
If a column is made for date values (DATE), if you are visually providing its value in a Table window, type the sections of the date using one of the following formulas:
Data Entry on Time-Based Columns
To specify the time value of a TIME-based column, use one of the following formulas:
fractional-seconds]
If the column was created for a date/time combination that uses the DATETIME or the SMALLDATETIME, start with the date follow by the time. Both sections must follow the formulas we reviewed for date and time values.
Practical Learning: Performing Visual Data Entry
Photo Identification | Camera Number | Violation Location | Vehicle Tag Number | Media Transfer Date | Media Transfer Time | Violation Period | Service Vehicle | Payment Due Date | Amount Due |
1 | LGU-602049 | Sommerset Rd and Clarenton Blvd | BPT-3095 | 13-June-2018 | 20:12:44 | 05/27/2018 06:18:05 AM | 0 | 08/02/2018 | 60 |
2 | M-280468 | 16-Jul-2018 | 11:32:38 AM | 10/25/2018 | 1 | 09-16-2018 | 125 | ||
3 | QGD-309586 | Union Crt | 850684 | 10-04-2018 | 10:08:12 | 21-September-2018 02:18:13 AM | 0 | 08--Nov-18 | 75 |
Fundamentals of Data Entry Using SQL
Introduction
To perform data entry using SQL, use the INSERT combined with the VALUES keywords. The primary formula to follow is:
INSERT table-name VALUES(Column1, Column2, Column_n);
Inserting INTO a Table
Alternatively, or to be more precise, you can use the INTO keyword between the INSERT keyword and the table-name. This is done with the following formula:
INSERT INTO table-name VALUES(Column1, Column2, Column_n)
The table-name doesn't exist. Consequently, you would receive an error.
The VALUES keyword indicates that you are ready to list the values of the columns. The values of the columns must be included in parentheses.
Data Entry for Characters and Strings
Introduction
If a column is made for a character (CHAR or VARCHAR) or a string, if you are providing its value in SQL, include the value in single quotes. Here is an example:
'M'
Data Entry for Unicode Characters
We saw that Microsoft SQL Server supports Unicode characters using the NCHAR and Unicode strings using the NCHAR() and the NVARCHAR() data type. If you are providing a value for such a column, precede the first single-quote with N. Here are examples:
N'Julius', N'Nyerere'
If you apply any of the variants of the char data type, the field can store up to 231 characters.
Data Entry for Number-Based Columns
Data Entry for Natural Numbers
To specify the value of a natural number-based column (INT, INTEGER, BIGINT, SMALLINT, or TINYINT), simply provide its value.
Data Entry for Decimal Numbers
As mentioned earlier, if a column is using a floating-point number (FLOAT, REAL, DECIMAL, or NUMERIC), if you don't need precision, provide its value in a natural number format. Here are examples:
Distance decimal
int a decimal number (decimal or numeric data types), you have the option of specifying or not indicating a precision. If you don't specify a precision, the decimal and numeric data types are treated as integers. This means that if you provide a fractional part, the number would be converted to integer. For example, 3.33 would be converted to 3 and 3.67 would be converted to 4.Microsoft SQL Server allows you to specify the amount of precision you want. The value must be an integer between 1 and 38. To specify the precision of a decimal or numeric-based column, add the parentheses after its data type and enter the number you want. Here is an example:
Scaling Data Entry on Decimal Numbers
money and smallmoney) and decimals (numeric and decimal). If a column is using a decimal or numeric data type, you can specify the amount of scale you want. The value must be an integer between 0 and 18.
To specify the scale of a decimal or numeric scale. . Here are examples:
5, 2 5, 2
This would produce:
Letter Grade | Min Range | Max Range | Min % | Max % | |
A | 4 | 95 | 100 | ||
A- | 4 | 4 | 90 | 94 | Excellent |
B+ | 3 | 4 | 85 | 89 | Good |
B | 3 | 3 | 80 | 84 | Good |
B- | 3 | 3 | 75 | 79 | Good |
C+ | 2 | 3 | 70 | 74 | Satisfactory |
C | 2 | 2 | 65 | 69 | Satisfactory |
C- | 2 | 2 | 60 | 64 | Satisfactory |
D+ | 1 | 2 | 55 | 59 | Satisfactory |
D | 1 | 1 | 50 | 54 | Satisfactory |
F | 0 | 1 | 0 | 49 | Unsatisfactor |
Data Entry for Date and Time Values
Data Entry for Date-Based Columns
DATE
Here is an example:
'2018-06-17'); GO
If your date value may include international formats, you can precede the value with N
Notice that, when using SQL, you can also use the YYYYMMDD formula. Here is an example:
N'19880617'
Data Entry on Time-Based Columns
To specify the value of a time-based column (TIME), include the value in single-quotes. If you want to handle international formats, start the value with N.
Data Entry for a Combination of Date and time
Data Entry for a Boolean Type
Introduction
BIT. Here are examples:
BIT N'28-400', 0); N'99284', 1); N'72844', -586); N'40-050', 82605); GO
Alternatives to Bits
The BIT
. Here is an example:
IsFullTime NVARCHAR(6)
);
or On and Off.
Data Entry With Other Data Types
Transact-SQL provides the sql_variantcolumn's data type, to perform data entry, use the appropriate format depending on the intended type, whether it is a string, a number, or a date, etc. Here are examples:
'Paul', N'Yamo', N'04-07-2012'
Spatial Types
Transact-SQL provides the geometry data type to support geometric coodinates. Unlike the other data types, the geometry type is in fact a class, like a class in C#. As a result, it has properties and methods. The properties of the geometry type are defined by the Open Geospatial Consortium (OGC). To adapt the data type to Transact-SQL, Microsoft added some functionalities to the type.
After specifying geometry as the data type of a column, you can set its values. To support this, the class is equipped with a method named STGeomFromText. Its syntax is:
static geometry STGeomFromText('geography_tagged_text', SRID)
geometry::STGeomFromText. This method returns a value or type geometry. Here is an example:
CREATE TABLE PictureLocation ( PictureName nvarchar(50), Coordinate geometry ); GO INSERT INTO PictureLocation(PictureName, Coordinate) VALUES(N'IMG001.jpg', geometry::STGeomFromText(. . .); GO
If you know the coordinates of a point and you want to use it as the value of the geometry object, type point() (or POINT(), this is not case-sensitive) and, in the parentheses, type both values separated by a space. Here is an example:
geometry::STGeomFromText('point(6 4)', . . .);
Instead of just one point, you may want to use a geometric value that is a line. In this case, specify the shape as linestring(, ). In the parentheses and on both sides of the comma, type each point as x and y. Here is an example:
geometry::STGeomFromText('linestring(1 4, 5 2)', . . .);
You can also use a complex geometric value, in which case you can pass the argument as a polygon. Use polygon(()) (or POLYGON(())) and pass the vertices in the parentheses. Each vertext should specify its x and y coordinates. The vertices are separated by commas. A last vertex should be used to close the polygon, in which case the first and the last vertices should be the same. Here is an example:
geometry::STGeomFromText('polygon((1 2, 2 5, 5 5, 4 2, 1 2))', . . );
The second argument of the geometry::STGeomFromText method is a contant integer known as the spatial reference ID (SRID). Here is an example:
VALUES(N'IMG001.jpg', geometry::STGeomFromText('point(6 4)', 0));
GO
After creating a UDT and setting it as the data type of a column, you can specify its value. Here are examples:
'28-380', N'Gertrude', N'Monay', N'1044 Alicot Drive', 26.75, 1); GO
code.
Starting a Graphical Application
Introduction to the .NET Framework
Text
Here is an example:This would produce:
This would produce:
Practical Learning: Performing a Compound Addition on Delegates
Characteristics of a Web Page Layout
The Anonymous Page Object of a Web Page
. This property is actually a member of the . T
Practical Learning: Setting the Caption of a Label
Introduction to the Button Control
Overview
Clicking a Button
. Here is an example:
Converting a Value to a Natural Number
text
Introduction to the Array Class
Overview
To
Introduction
for.
Practical Learning: Executing the Application
The. Here is an example:
The Mouse Up Message
ollows:
Introduction
To support drag n'
Introduction
When you are cr
The an enumeration.
the
based on the
same value. Here is an example:
To . Its syntax is:
Control's Construction and Destruction
. Here is an example:
is:
. Here is an example:
Introduction to Colors on Windows Controls
Using a Visual C++/CLI Library
One
In
Checking a Class Member for Nullity
a valid value. Here is an example:
The
Accessing the Members of an Array
Declaring a Delegate
Using a Non-Integer-Based Index
an example of a float array:
Fundamental Built-In Generic Interfaces
Introduction
interfaces.
The
This would produce:
where condition. Here is an example:
This would produce:
Characteristics of
Introduction to the ICollection Generic Interface
The
:
.
Practical Learning: Saving Data
[Serializable]
<
[Serializable]
numbers = list
Fundamentals of Creating a Collection Class
The Number of Items in a Collection
Consequently, you must implement both methods in neric collection class. Here are examples:
Characteristics of Enumerable
A Read-Only Collection
The : ICollection<.
Data Analysis on Queries
Adding an Item
the IList<> interface:
::
the IList<> interface:
Introduction to the Items of a Collection
Inserting an Item
IList<interface provide a method named
class.
Getting the Index of an Item
The the in the class that T represents.This would produce:
ICollection<. Its syntax is:
A Parameterized Functionm
Additional Operations on a Collection
Introduction
The
Adding a Collection to a Collection
. Here is an example:
Replacing an Item
. Here is an example:
Moving an Item
.
view associated with the method, type and its square brackets. In the square brackets, pass the name you had used.address
Swapping Items
This would produce:
Here is an example of how this can be done:
Starting a Graphical Application
Introduction to the .NET Framework
he variable. Here is an example:
This would produce:
Details on Creating a Form
The Controller of a Form
ecify in what controller class some of the processing will be done.
The Action that Processes a Form
d argument is the name of the controller that contains the code that processes the form. The first argument is a string that is the name of the method that processes the form. Normally, this method is an action. Thereform, the method should an ActionResult-type of object.
The Name of a Form
IList< generic interface inherits. Its syntax is:
Getting an Item from a Collection
the controller class, t object:
The Height of a Form
the To specify the .
Delegates
Introduction
s.
Declaring a Delegate
Here is an example:
Application: Creating a Stream
This would produce:
A Helping Static Class
Introduction
If a property is intended to be read-write, create it without its body in the interface. , you must define each of the interface's method.
Practical Learning: Adding a Method to an Interface
ere is an example:
You can also declare the variable and allocate its memory on the same line. Here is an exampleAfter that, you can use the object.
Practical Learning: Passing an Interface As Argument
Practical Learning: Returning an Interface
The Last Item of a Collection
This WebPage class.To let you add a webcontrol to a form, the HtmlHelper class is extended with various overloaded methods for different HTML objects. The methods are TextBox() for a text box, CheckBox() for a check box, RadioButton() for a radio button. The simplest version of each method takes only one argument. FoAs seen in previous lessons, there are two primary things you need to do in order to process the controls of a form. To start, create and INPUT control of type SUBMIT. Here is an that contains a contional statement that checks the value of an IsPost property:
Practical Learning: Creating an Interface
For example, you can access its members. Here is an example:
ICollection.
The ICollection<> interface. The only real functionalities of the nested KeyCollection class are its ability to know the current number of items in the list and the ability to enumerate the members of the collection through a foreach loop.
KeyCollection System.Collections.Generic.Dictionary, the SortedDictionary, and the System.Collections.Generic.SortedList classes are equipped with the nested ValueCollection. The ValueCollection serializable class implements the ICollection<> and the IEnumerable interfaces. The functionality of the ValueCollection class is the same as its counterpart of the System.Collections namespace.
Application: Writing to a Stream
We have seen that the and the Contains() call a method named ContainsKey.
The syntax of the ey() and the ContainsKey() method is:
The syntax of the System and the System method is:
null. Here is an example:null to the variable. Other than that, at any time, before accessing a member of the class, you should first check whether the variable is null or not. To let you get this information, the C# language provides the is operator. To use it, create a conditional operator using the following formula:
Practical Learning: Enumerating the Members of a Collection
Creating a Recursive Method
This would produce:
This would produce:
This would produce:
This would produce:
This would produce:
This would produce:
Practical Learning: Using the Anonymous Page Object
Controlling Access to a View
Introduction to Controllers
So ay the value of a member a for loop re-initialize the array by allocating new memory to it.
Practical Learning: Introducing Controllers
Checking Whether an Object IS Null
the operator. To use it, create a conditional operator using the following formula:
(
. Here is an example:
. Here is an example:This would produce:
Checking for Nullity
Comparing an Object to Nullity
ight operand. Here is an example:
es point to the same object, the comparison produces a .
The Null-Conditional Operator
. Here is an example:
Here is another version of the code:
The Null Coalescing Operator
. Here is an example:
A Null Field
k to it. Here are examples:
?
A Null Value for a Primitive Type
This would produce:
This would produce:
. Here is an example:
Introduction to Nullity
The Nullity of a Variable
.
A Null Object
Imagine you want to create an object from an interface or a class:
. Here are examples:
Here is an example:
This would produce:
This would produce:
This would produce:
A regular formula to use a read-write property is:
index] = value
The Path to a File
e. An example would be
Here is an example:
I. Here are examples:
.
.
Introduction to the Label Control
Overview of Labels
method. Here is an example:
method.
l. Here are example:
. In the parentheses, pass the name of the control.
property and assign the desired integer to it.
Practical Learning: Setting the Left Posittion of a Control
The Top Position of a Control
. Toit.
Practical Learning: Specifying the Top Position of a Control
;
The Text of a Control
. he value of its
Practical Learning: Setting the Caption of a Label
The Width of a Control
.
Practical Learning: Specifying the Width of a Control
The Height of a Control
Practical Learning: Introducing Events
Practical Learning: Introducing Events
Converting a Value to a Natural Number
The basic formula to convert text to a decimal number is:The description is the same as for the integer.
Converting a Value to Text
This would produce:
AAA
A Delegate That Takes One of More Arguments
returns a value):
delegate double Addition(double x, double y);
Here is an example:
. Here is an example:
plate.)
the delegate.
public virtual void Clear()
A Delegate Passed as Argument
A delegate. Here is an example:
You. Here is an example:
Introduction to the Location
the.
Checking for Nullity
Comparing an Object to Nullity
}
null keyword as the right operand. Here is an example:
}
. Here is an example:
Checking Whether Two Objects Use the Same Reference
When you are dealing with result. Otherwise, the comparison is false types of objects in a section of code, you may be interested in comparing two objects. This operation can be performed using the
comparison-result = object1 is object2
object is null. To simplify this operation, the C# language provides the null-conditional operator represented as ?. (the question mark immediately followed by a period). To apply it, use it to access the member of a class. Here is an example:
. If it doesn't, then the member on its right is accessed and the operation that must be performed proceeds.
This code states that if the House object is null, the beds variable should be assigned 0. If the House object is not null, then the beds variable should receive a value from the designated property of the House class:
Checking Whether an Object IS Null
As seen earlier, variable statement(s)when declaring a variable for a class, if you are not ready to create an object, you can assign
StreamReader object, make sure you close it.
with a method named Open that is overloaded with three versions. If the file you want to use is text-based, to assist you in opening it, the FileInfo class is equipped with a method named OpenText. Its syntax is:
structureclassesperforms the action you want. Here is an example:
The DictionaryEntry
)
TopBase * Length; BottomBase * Length;
: base(parameter(s) )
: base()
double rad) : base(rad)
: base(fName, lName)
double salary) HourlySalary = salary;
public
public
this. this.
double
txtElement2.Top = 22; txtElement2.Left = 185; txtElement2.Width = 70; txtSymbol1.Top = 48; txtSymbol1.Left = 110; txtSymbol1.Width = 70; ; frmChemistry.Controls.Add(txtSymbol1); txtSymbol2 = new TextBox(); txtSymbol2.Top = 48; txtSymbol2.Left = 185; txtSymbol2.Width = 70; ; txtAtomicNumber1 = new TextBox(); txtAtomicNumber1.Top = 74; txtAtomicNumber1.Left = 110; txtAtomicNumber1.Width = 70; txtAtomicNumber1); = new TextBox(); .Top = 74; .Left = 185; 1 = new TextBox(); 1.Top = 100; 1.Left = 110; 1.Width = 70; frmChemistry.Controls.Add(1); "Category:"; txtCategory1.Top = 126; txtCategory1.Left = 110; txtCategory1.Width = 70; txtCategory1); = new TextBox(); .Top = 126; .Left = 185; .Width = 70; frmChemistry.Controls.Add(); Category = "Alkali Metal"; Symbol = "Cs"; 55; "Caesium"; AtomicWeight = 132.90545196; txtSymbol1.Text = Symbol; txtElement1.Text = Element; txtAtomicNumber1.Text = AtomicNumber.ToString(); 1.Text = AtomicWeight.ToString(); 87; "Francium"; Symbol; txtElement2.Text = Element;
A Re-Introduction to Windows Controls
A Windows Control as a Class
Introduction to the Members of a Class
Introduction to the Properties of a Class
Throughout our lessons, we will find out what the starting options are (for now, let's ignore that). By the way, unlike some languages, C# doesn't use as a keyword.
The Main Function of an Application
Here is an example of checking the existence of a file: Here is an example of what this would produce:
value Size value Rectangle efine a Point and a Size
In the same way, you can negate a where ..
namespace provides the RectangleF structure that uses the same definition as Rectangle, except that it is defined with float values instead of integers.
The Bounds. Rectangle Dictionay Bounds property Rectangle value.
ALTER TABLE table-name
ncrement statement(s)
In this formula, the for keyword, the parentheses, and the semi-colons are required. The data-type is used to specify how you will count the members of the array.
The Initializer initialization could use an initialized int-based variable.
(<, <=,
The Increment factor specifies how you would move from one index to the next.
When using a for loop, you for pay attention to the number of items you use. If you use a number n less than the total number of members - 1, only the first n members of the array would be accessed. Here is an example:
Looping Through an Array of Items
Going For Each Item in the Array
You can use the operator to visit each member of the array. In this case, you don't need the GetValue() method. Here is an example:
}
Practical Learning: Visiging Each Object of an Arrray
Practical Learning: Breaking the Flow of a Loop
Selecting a Value From a List
Introduction
This would produce:
. Here is an example:
This would produce:
IEnumerable expression. Here is an example:
This would produce:
Size
Result: All controls,trol:
Common Properties of Controls
TextAlignfield:
The TextAlign property is of type ContentAlignment
ContentAlignment enumeration. Here is an example:
The ability to manage a control or a group of controls' location and size when the user resizes it is done using the Anchor property:
The
Bottom: The control bottom border will be the same even if the parent is heighten or shrunk
Left: The control left border will be the same even if the parent is widened or narrowed
Right: The control right border will be the same even if the parent is widened or narrowed
In the same way, you can combine AnchorStyles values to "glue"
This property is managed through the
Bottom
Fill: The control will use the whole client area of its parent.
Left: The control will be attached to the left border of its parent:
None: The control will be kept where it was positioned on the parent:
Right: The control will be attached to the right border of its parent:
Top: The control will be attached to the top border of its parent:
Aesthetic Aspects of a Control
Background Color
ControlProperties window:
enumeration called Color.
. Here is an example:
This would produce:
Background Image
Some controls display a border when they are drawn and some others don't. Consider the following:
the BorderStyle property, which is based on BorderStyle enumerator. Its members are:
BorderStyle. Here is an example:
False.
Practical Learning: Setting the Tab Order of Controls
Visible
At design time, when you add a control to a parent, it is visible by default. This is because its Visible property is set to True in the Properties window. In the same way, if you programmatically create a control, by default, it is made visible once you add it to its parent's Controls property.
If you don't want a control to primarily appear when the form comes up, you can either set its Visible property to False or set its parent’s visible property to False. Equivalently, at run time, to hide a control, assign a False value to either its Visible property or its parent’s Visible property. Keep in mind that when a parent gets hidden, it also hides its children. On the other hand, a parent can be made visible but hide one or some of its children.
To programmatically check whether a control is visible at one time, apply a conditional statement ( or while) to its Visible property and check whether its value is true or false.
public void Show();
By default, after adding a control to a form, it is enabled and its Enabled property in the Properties window is set to True. An enabled control displays its text or other characteristics in their normal settings. If you want to disable a control, set its Enabled property to False. In the following picture, a text box and a button are disabled:
A text-based control indicates that it has focus by displaying a blinking cursor. A list-based control indicates that it has focus when one of its items has a surrounding dotted rectangle:
Focus() method. Its syntax is:
After GetTopLevel() s:
Practical Learning: Introducing the Characteristics of Windows Controls
The Content Alignment of a Text Box
Here is an example:List<Student> attendees = pupils.ToList();
You can then use the List<> variable as you see fit.the ToArray() and the The syntax of the ToArray() method is:the in a variable created in a from
public static TSource[] ToArray<TSource>( this IEnumerable<TSource> source;)
To store the results of an IEnumerable
var std in attendees
Instead of first creating the select list, then declaring an array variable, you can include the LINQ statement in parentheses and call the ToArray() method outside the closing parenthesis. Here is an example:
Instead of storing the result of a LINQ statement into an array, you can store it in a collection. To support this, the IEnumerable interface is equipped with the ToList() method
field. It is based on an enumeration named . When you click OK, s .For example, if you have a list of students, you may want the list to be organized by gender, or by another category. storing the results in a select variable, and the select variable was able to provide its list when necessary. We also learned how to sort the values in a select list. As an alternative,
Practical Learning: Aligning the Content of a Text Box
var age = 14;
Student[] pupils = (
select studs
interface is equipped with the ToList() method. Its syntax is:
public static List<TSource> ToList<TSource>( this IEnumerable<TSource> source);
ToArray() a List<>. Here is an example:
IEnumerable<Student>
List<Student>
List<>
This would produce:
This would produce:
This would produce:
This would produce:
This would produce:
This would produce:
Introduction to the Helpers
Overview
:
. Here is an example:
.
Calling a Helper
Introduction to Parameters and Arguments
Introduction to the Parameters of a Helper
string:
string
. Here is an example:
typeOfRoof) typeOfRoof
.
Calling a Helper that Uses a Parameter
.
. Here is an example:
. Here is an example:
string roofMaterial = "Asphalt Shingles"; ProtectFromBadWeather(roofMaterial);
The parameters can also be of different types. Here is an example of a helper that uses 3 parameters:
string
As mentioned earlier, you don't have to use the parameters in the body of the helper if you don't have use for it. Otherwise, in the body of the helper, you can use the parameters any appropriate way you want.
When calling a helper that uses many parameters, you must provide a value for each parameter in the order the parameters appear in the parentheses.
A variable is said to be local if it is declared in the body of a helper. Here is an example:
class MemberRegistration
{
private void Create()
{
string middleName;
}
}
. Here is an example:
Here is an example:
Helpers and Class
The Scope and Lifetime of an Object
Once this has been done, the object is ready to be used by any helper of the same class. As an alternative, you can declare the variable in the body of the class but initialize it in a helper of the class. Here is an example:
To present the value to the console window, pass the name of the variable in the parentheses of . Here are examples:
);
You can also use Here is an example:
Remember that, in the body of the helper, you can use or ignore the parameter. Still, when calling the helper, you must provide a value for the parameter. Here is an example:
This would produce:
In the same way, you can create a helper that uses various parameters that are of type . Here is an example:
}
Practical Learning: Disposing of Components
Practical Learning: Creating a Helper
<h2 style="text-align: center">Binary Classification</h2>
@Describe()
Practical Learning: Using Local Variables in a Helper
Practical Learning: Creating an Interface
Amount to Allocate: 6540 Portion 1: 5 Portion 2: 3
Practical Learning: Using a Local Object
Practical Learning: Adding a Property to an Interface
public
Here is an example:
double
In the same way, you can add as many methods as you want. In every class or structure that implements the interface, you must define each of the interface's method.abstract, ,
Practical Learning: Adding a Method to an Interface
publi
IPolygon figure;
When allocating memory for the object using the new operator, you must use a class that implements that interface. Here is an example:You can also declare the variable and allocate its memory on the same line. Here is an example:After that, you can use the object.
If you use any of these two techniques, you can access only the members of the interface. The non-interface members of the class would not be available. As a result, the following code would produce an error:
IPolygon et et.Height
Practical Learning: Declaring a Variable of Interface Type
Practical Learning: Passing an Interface As Argument
private void Display(IPolygon poly) { .Edges.ToString(); txtInternalAngle.Text = .InternalAngle.ToString(); txtInscribedRadius.Text = .CalculateInscribedRadius().ToString(); txtCircumscribedRadius.Text = .CalculateCircumscribedRradius().ToString(); txtPerimeter.Text = .Perimeter.ToString(); txtArea.Text = .Area.ToString(); } private void btnCalculate_Click(object sender, EventArgs e) { double measure = Convert.ToDouble(txtSide.Text); IPolygon = new Pentagon(measure); Display(shape);
Practical Learning: Returning an Interface
private IPolygon Create() { double measure = Convert.ToDouble(txtSide.Text); IPolygon shape = new Pentagon(measure); return Create()
Inheriting an Interface
An interface can be derived from another interface (but an interface cannot derive from a class). Obviously the derived interface is supposed to add some behavior using methods and/or properties. Here is an example:
interface IPolyhedron : IPolygon
{
double Volume { get; set; }
}
As you should know already that nothing is implemented in an interface, a member of the parent interface cannot be defined in a derived interface. Also, any class that needs the behavior(s) of the derived interface must implement all members of the derived interface and those of the parent interface(s). Here is an example:
Implementing Many Interfaces
. Here is an example:
In the above example, we created a class that implements only two interfaces. You can create a class that implements as many interfaces as you want. Also, the same interface can be implemented differently in different classes.
Practical Learning: Introducing Integers
private void btnClose_Click(object sender, EventArgs e) { Close(); }
|
private void btnCalculate_Click(object sender, EventArgs e) { double priceContainer = 0.00, priceIngredient = 0.00, priceScoops = 0.00, orderTotal = 0.00; int numberOfScoops = 1; // Find out what container the customer requested // The price of a container depends on which one the customer selected if (txtContainer.Text == "Cone") priceContainer = 0.55; else if (txtContainer.Text == "Cup") priceContainer = 0.75; else priceContainer = 1.15; // If the customer selected an ingredient, which is not "None", add $.95 if (txtIngredient.Text != "None") priceIngredient = 0.95; // Get the number of scoops numberOfScoops = int.Parse(this.txtScoops.Text); if (numberOfScoops == 2) priceScoops = 2.55; else if (numberOfScoops == 3) priceScoops = 3.25; else priceScoops = 1.85; // Make sure the user selected a flavor, // otherwise, there is no reason to process an order if (txtFlavor.Text != "") orderTotal = priceScoops + priceContainer + priceIngredient; this.txtOrderTotal.Text = orderTotal.ToString("F"); btnMoneyChange.Enabled = true; }
"Cone"; txtIngredient.Text = "None"; txtScoops.Text = "1"; txtOrderTotal.Text = "0.00"; btnMoneyChange.Enabled = false; }
|
"F"
"F"
;
|
Practical Learning: Introducing Loops
Practical Learning: Creating a While Loop
Run
Presenting a Character
As seen for the other types of variables, to make it possible to display a character to the console, the class is equipped with a version that takes a character as argument. Its syntax is:
value);
This would produce:
Here is an example:
This would produce:
If you want to move to the next line after displaying the character, the Console class provides the following version of the WriteLine() method:
Control | (Name) | Text |
Label | New Password: | |
TextBox | txtNewPassword | |
TextBox | txtCharacters | |
Label | Characters |
);
Here are examples of calling this method:
This would produce:
Practical Learning: Overloading an Indexer
. . . No Change
Introduction
When a program starts, it looks for an entry point. This is the role of the Main() function. In fact, a program, that is an executable program, starts by, and stops with, the Main() function. The way this works is that, at the beginning, the compiler looks for a function called . If it doesn't find it, it produces an error. If it finds it, it enters the Main().
This would produce:
T
Here are examples:
This would produce:
number
members.GetValue(List , Element ));
If you want the user to provide additional information when executing your program, you can take care of this in the Main() function. Consider the following code written in a file saved as Exercise.cs:
102 44 525 38 6 28 24481 327 632 104 After deleting the third item... 0 0 0 0 0 0 0 0 0 0 Press any key to continue . . .
Gender: Female Length: 6 Characters Press any key to continue . . .
0
0 0 0
To execute the application, at the Command Prompt and after Changing to the irectory that contains the file, you would type
and press Enter. To execute the program, you would type the name Exercise and press Enter. The program would then prompt you for the information it needs.
The above program produces:
csc to the Main().
.
Here is an example:
Here is an example:
This would produce:
Here is an example:
This would produce:
Finally, where you call this new method, pass the name of the method that is associated to the delegate. This can be done as follows. Here is an example:
var videos = from vdos in lstVideos group vdos by vdos.Rating into categories where categories.Contains(lstVideos[0]) select categories;
Finally, where you call this new method, pass the name of the method that is associated to the delegate. This can be done as follows. Here is an example:
Practical Learning: Grouping the Categories
Grouping Into a Variable
When you create a grouping, you get a list of categories of values and that list becomes ready to be used. In some cases, before exploring the list, you may want to perform an operation on it. One way you can do this, you can store that list in a (local) variable and use that variable as if it were a from variable.
To declare a variable to store the grouping values, you use the into contextual keyword through the following formula:
var SubListName = from ValueHolder
in List
group ValueHolder by Category into GroupVariable ...;
The GroupVariable is the new factor in our formula. You specify it as a regular name of a variable. Here is an example:
var empls = from staffMembers
in employees
group staffMembers by staffMembers.Gender into Categories
After creating the name, you can perform any operation on it inside the LINQ statement. The variable is of type IGrouping. This means that you can access its Key property or you can access one of the methods that the interface gets from IEnumerable, and then use it as you see fit. Here is an example:
var empls = from staffMembers
in employees
group staffMembers by staffMembers.Gender into Categories
where Categories.Contains(students[0])
Before ending the LINQ statement, you must create either a group...by expression or a select statement that uses the into variable. Here is an example:
This statement, particularly the Enumerable.Contains(lstVideos[0])
This would produce:
In the same, to get the category stored in the second index of the grouping, you would use Enumerable.Contains(lstVideos[1]). Of course this means that you can use grouping and the into operator to get a list of items of only one particular category.
Although the GroupVariable can be selected or grouped...by, it cannot be used outside the LINQ statement. It is only available in the local LINQ expression.
and press Enter. To execute the program, you would type Exercise followed by a first name, a last name, and two decimal values. An example would be Exercise Catherine Engolo 42.50 20.48
Practical Learning: Creating an Empty Set
public Algebra()
{
InitializeComponent();
}
private void Algebra_Load(object sender, EventArgs e)
{
A = new HashSet<int>();
}
}
}
This would produce:
As you can see, this method returns a string array that represents the arguments to the command line.
To assist you with getting the information about the command line of an application, the Environment class provides a property named CommandLine. Here is an example of accessing it:
Environment.CommandLine
. Here is an example:
After creating the property, you can use it. To do this, you must pass an object that is the type of the index. You can then use the returned value as you see fit. Here is an example:
This would produce
This would be done as follows:
This would produce:
Practical Learning: Checking for Super-Set
This would produce:
Consider the following list:
Notice that some records don't have a value for some fields (such as the DirectorID property); they are empty.
You can also directly pass an instance of the class in the square brackets of the object that holds the indexed property, as long as you specify the object. Here is an example:
Practical Learning: Introducing Collection Iteration
Action<string>
Practical Learning: Enumerating a Collection
using
payments = new Collector
private
private void btnClose_Click(object sender, EventArgs e) { Close(); }
Unit Code | Aprt # | Bedrooms | Bathrooms | Monthly Rate | Occupancy Status | |
399475 | 101 | 2 | 2 | 1150 | 650 | Available |
508293 | 102 | 1 | 1 | 950 | 500 | Needs Repair |
729397 | 103 | 1 | 1 | 925 | 500 | Available |
928364 | 104 | 3 | 2 | 1350 | 850 | Available |
297297 | 105 | 2 | 1 | 1150 | 550 | Available |
492739 | 106 | 3 | 2 | 1350 | 850 | Available |
692797 | 107 | 3 | 2 | 1285 | 850 | Not Ready |
829475 | 108 | 1 | 1 | 885 | 500 | Available |
139749 | 109 | 2 | 2 | 1150 | 650 | Available |
369294 | 110 | 1 | 1 | 895 | 500 | Available |
502084 | 111 | 2 | 2 | 1145 | 650 | Available |
829397 | 112 | 2 | 1 | 1085 | 600 | Available |
292739 | 201 | 2 | 1 | 1185 | 650 | Available |
496055 | 202 | 1 | 1 | 895 | 500 | Available |
939595 | 203 | 1 | 1 | 925 | 500 | Available |
384068 | 204 | 3 | 2 | 1250 | 850 | Available |
824850 | 205 | 2 | 1 | 1100 | 600 | Available |
620485 | 206 | 3 | 2 | 1300 | 850 | Available |
294940 | 207 | 3 | 2 | 1350 | 850 | Available |
602048 | 208 | 1 | 1 | 920 | 500 | Available |
829479 | 209 | 2 | 2 | 1150 | 650 | Available |
280484 | 210 | 1 | 1 | 895 | 500 | Available |
602408 | 211 | 2 | 2 | 1175 | 650 | Available |
384086 | 212 | 2 | 1 | 1075 | 600 | Available |
397493 | 301 | 2 | 2 | 1175 | 650 | Available |
625941 | 302 | 1 | 1 | 950 | 500 | Available |
404950 | 303 | 1 | 1 | 925 | 500 | Available |
304806 | 304 | 3 | 2 | 1250 | 850 | Available |
844850 | 305 | 2 | 1 | 1100 | 600 | Needs Repair |
596305 | 306 | 3 | 2 | 1300 | 850 | Available |
138408 | 307 | 3 | 2 | 1350 | 850 | Available |
305860 | 308 | 1 | 1 | 920 | 500 | Available |
847584 | 309 | 2 | 2 | 1150 | 650 | Available |
746959 | 310 | 1 | 1 | 935 | 500 | Available |
359405 | 311 | 2 | 2 | 1175 | 650 | Available |
308505 | 312 | 2 | 1 | 1075 | 600 | Available |
Practical Learning: Combining Various Disjunctions
"1")H") h; } 2 He")he; } 3 Li")li; } 4 Be")be; } 5")B") b; } 6")C") c; } 7")N") n; } 8")o") o; } 9")F") f; } 10 Ne")ne; } 11 Na")na; } 12 Mg")mg; } 13 Al")al; } 14 Si")si; } else if(
@helper SelectElement(string valueEntered) { Chemistry08.App_Code.Element selected = new Chemistry08.App_Code.Element(); Chemistry08.App_Code.Element h = new Chemistry08.App_Code.Element(1, "H", "Hydrogen", 1.008M) { Phase = Chemistry08.App_Code.Phase.Gas }; Chemistry08.App_Code.Element he = new Chemistry08.App_Code.Element(2, "He", "Helium", 4.002602M) { Phase = Chemistry08.App_Code.Phase.Gas }; Chemistry08.App_Code.Element li = new Chemistry08.App_Code.Element(3, "Li", "Lithium", 6.94M) { Phase = Chemistry08.App_Code.Phase.Solid }; Chemistry08.App_Code.Element be = new Chemistry08.App_Code.Element(4, "Be", "Beryllium", 9.0121831M) { Phase = Chemistry08.App_Code.Phase.Solid }; Chemistry08.App_Code.Element b = new Chemistry08.App_Code.Element(5, "B", "Boron", 10.81M) { Phase = Chemistry08.App_Code.Phase.Solid }; Chemistry08.App_Code.Element c = new Chemistry08.App_Code.Element(name: "Carbon", mass: 12.011M, symbol: "C", number: 6) { Phase = Chemistry08.App_Code.Phase.Solid }; Chemistry08.App_Code.Element n = new Chemistry08.App_Code.Element(7); n.Symbol = "N"; n.AtomicWeight = 14.007M; n.ElementName = "Nitrogen"; n.Phase = Chemistry08.App_Code.Phase.Gas; Chemistry08.App_Code.Element o = new Chemistry08.App_Code.Element("O") { AtomicNumber = 8, ElementName = "Oxygen", AtomicWeight = 15.999M, Phase = Chemistry08.App_Code.Phase.Gas }; Chemistry08.App_Code.Element f = new Chemistry08.App_Code.Element("F") { AtomicNumber = 9, ElementName = "Fluorine", AtomicWeight = 15.999M, Phase = Chemistry08.App_Code.Phase.Gas }; Chemistry08.App_Code.Element ne = new Chemistry08.App_Code.Element("Ne") { AtomicNumber = 10, ElementName = "Neon", AtomicWeight = 20.1797M, Phase = Chemistry08.App_Code.Phase.Gas }; Chemistry08.App_Code.Element na = new Chemistry08.App_Code.Element(11, "Na", "Sodium", 22.98976928M) { Phase = Chemistry08.App_Code.Phase.Solid }; Chemistry08.App_Code.Element mg = new Chemistry08.App_Code.Element(12, "Mg", "Magnesium", 24.305M) { Phase = Chemistry08.App_Code.Phase.Solid }; Chemistry08.App_Code.Element al = new Chemistry08.App_Code.Element(13, "Al", "Aluminium", 26.9815385M) { Phase = Chemistry08.App_Code.Phase.Solid }; Chemistry08.App_Code.Element si = new Chemistry08.App_Code.Element() { ElementName = "Silicon", AtomicWeight = 28.085M, Symbol = "Si", AtomicNumber = 14, Phase = Chemistry08.App_Code.Phase.Solid }; Chemistry08.App_Code.Element p = new Chemistry08.App_Code.Element() { ElementName = "Phosphorus", AtomicWeight = 30.973761998M, Symbol = "P", AtomicNumber = 15, Phase = Chemistry08.App_Code.Phase.Solid }; if ( "1")H") h; } 2 He")he; } 3 Li")li; } 4 Be")be; } 5")B") b; } 6")C") c; } 7")N") n; } 8")o") o; } 9")F") f; } 10 Ne")ne; } 11 Na")na; } 12 Mg")mg; } 13 Al")al; } 14 Si")si; } 15")p") p; } <form name="frmChemistry" method="post"> <table> <tr> <td class="left-col emphasize">Atomic Number:</td> <td><input type="text" name="txtAtomicNumber" value=@selected.AtomicNumber /></td> </tr> <tr> <td class="emphasize">Symbol:</td> <td><input type="text" name="txtSymbol" value=@selected.Symbol /></td> </tr> <tr> <td class="emphasize">Element Name:</td> <td><input type="text" name="txtElementName" value=@selected.ElementName /></td> </tr> <tr> <td class="emphasize">Atomic Weight:</td> <td><input type="text" name="" value=@selected.AtomicWeight /></td> </tr> <tr> <td class="emphasize">Phase:</td> <td><input type="text" name="" value=@selected.Phase /></td> </tr> </table> </form> }
Practical Learning: Combining Various Disjunctions
"H", "Hydrogen", 1.008M) { Phase = Chemistry08.App_Code.Phase.Gas };
Chemistry08.App_Code.Element he = new Chemistry08.App_Code.Element(2, "He", "Helium", 4.002602M) { Phase = Chemistry08.App_Code.Phase.Gas };
Chemistry08.App_Code.Element li = new Chemistry08.App_Code.Element(3, "Li", "Lithium", 6.94M) { Phase = Chemistry08.App_Code.Phase.Solid };
Chemistry08.App_Code.Element be = new Chemistry08.App_Code.Element(4, "Be", "Beryllium", 9.0121831M) { Phase = Chemistry08.App_Code.Phase.Solid };
Chemistry08.App_Code.Element b = new Chemistry08.App_Code.Element(5, "B", "Boron", 10.81M) { Phase = Chemistry08.App_Code.Phase.Solid };
Chemistry08.App_Code.Element c = new Chemistry08.App_Code.Element(name: "Carbon", mass: 12.011M, symbol: "C", number: 6) { Phase = Chemistry08.App_Code.Phase.Solid };
Chemistry08.App_Code.Element n = new Chemistry08.App_Code.Element(7);
n.Symbol = "N";
n.AtomicWeight = 14.007M;
n.ElementName = "Nitrogen";
n.Phase = Chemistry08.App_Code.Phase.Gas;
Chemistry08.App_Code.Element o = new Chemistry08.App_Code.Element("O")
{
AtomicNumber = 8,
ElementName = "Oxygen",
AtomicWeight = 15.999M,
Phase = Chemistry08.App_Code.Phase.Gas
};
Chemistry08.App_Code.Element f = new Chemistry08.App_Code.Element("F")
{
AtomicNumber = 9,
ElementName = "Fluorine",
AtomicWeight = 15.999M,
Phase = Chemistry08.App_Code.Phase.Gas
};
Chemistry08.App_Code.Element ne = new Chemistry08.App_Code.Element("Ne")
{
AtomicNumber = 10,
ElementName = "Neon",
AtomicWeight = 20.1797M,
Phase = Chemistry08.App_Code.Phase.Gas
};
Chemistry08.App_Code.Element na = new Chemistry08.App_Code.Element(11, "Na", "Sodium", 22.98976928M) { Phase = Chemistry08.App_Code.Phase.Solid };
Chemistry08.App_Code.Element mg = new Chemistry08.App_Code.Element(12, "Mg", "Magnesium", 24.305M) { Phase = Chemistry08.App_Code.Phase.Solid };
Chemistry08.App_Code.Element al = new Chemistry08.App_Code.Element(13, "Al", "Aluminium", 26.9815385M) { Phase = Chemistry08.App_Code.Phase.Solid };
Chemistry08.App_Code.Element si = new Chemistry08.App_Code.Element() { ElementName = "Silicon", AtomicWeight = 28.085M, Symbol = "Si", AtomicNumber = 14, Phase = Chemistry08.App_Code.Phase.Solid };
Chemistry08.App_Code.Element p = new Chemistry08.App_Code.Element() { ElementName = "Phosphorus", AtomicWeight = 30.973761998M, Symbol = "P", AtomicNumber = 15, Phase = Chemistry08.App_Code.Phase.Solid };
Chemistry08.App_Code.Element s = new Chemistry08.App_Code.Element(16, "S", "Sulfur", 32.06M) { Phase = Chemistry08.App_Code.Phase.Solid };
if ( (valueEntered == "1hH") ) { selected = h; }
else if( (valueEntered == "2heHeHEhE")) { selected = he; }
else if( (valueEntered == "3liLiLIlI")) { selected = li; }
else if( (valueEntered == "4beBeBEbE")) { selected = be; }
else if( (valueEntered == "5bB") ) { selected = b; }
else if( (valueEntered == "6cC") ) { selected = c; }
else if( (valueEntered == "7nN") ) { selected = n; }
else if( (valueEntered == "8oO") ) { selected = o; }
else if( (valueEntered == "9Ff") ) { selected = f; }
else if( (valueEntered == "10neNeNEnE")) { selected = ne; }
else if( (valueEntered == "11naNANanA")) { selected = na; }
else if( (valueEntered == "12mgMgMGmG")) { selected = mg; }
else if( (valueEntered == "13alAlALaL")) { selected = al; }
else if( (valueEntered == "14siSiSIsI")) { selected = si; }
else if( (valueEntered == "15pP") ) { selected = p; }
else if( (valueEntered == "16") || (valueEntered
Looping Each Object
To access each member of the array, you can use the foreach operator that allows you to use a name for each member and omit the square brackets.
Practical Learning: Going for each Member of an Array
state state state.AreaSqrKms</td> <td class="text-center">@state.AdmissionUnionDate</td> <td class="text-center">@state.AdmissionUnionOrder</td> <td>@state.Capital</td> </tr> } </table>
Introduction to Collection-Based Controls
The Checked List Box
A checked list box is a combination of a list box and a series of check boxes. It appears as a list box where each item displays a check box to its left. Here is an example:
To support the checked list box, the .NET Framework provides a class named CheckedListBox. To visually creare a checked list box, use the CheckedListBox button from the Common Controls section of the Toolbox. To programmatically create a checked list box, declare a variable of type CheckedListBox and initialize it appropriately. Here is an example:
This would produce:
The Checked List Box
The items of a checked list box are store in a property named Items. To add an item to the control, call the Add() method on that property and pass at least a string. Here is an example:
This would produce:
You can also add an array of items by calling the and you can insert an item using the Insert() method. There are two ways a user can use a checked list box, by clicking an item or clicking a chec box:
The CheckOnClick
Practical Learning: Checking for Proper Sub-Set
}
Application: Introducing Streaming
The Server Path to a File
For better management and security, a file has attributes (characteristics) that indicate what can be done on the file or that provide specific information that the programmer or the operating system can use when dealing with the file.
Reading a Text File
. When you click OK, s .
One of the path, FileMode mode); of the :
, property is managed by a collection as in Both the key and the value are provided as strings. The value can be provided by the name of a control. The name of the control must be passed as a string. To give you access to the valueOr you can involve the value in an expression
Practical Learning: Creating a Stream
Opening a File
Delegates and Parameters
A Delegate that Uses a Parameter
Create a method that takes the delegate as parameter. Here is an example:
Another is to pass an additional parameter to the method. That other parameter would be used by the delegated method when it is called. Here is an example:
, 6284.57 , double n
Here is an example of accessing the value of the above scenario in a webpage:
public delegate void Factorizer(double x, int f);
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
}
When creating a method that takes the delegate as parameter, you can also pass additional parameters as the same numbers and types used in the delegate. In the body of the method, you can call the delegated parameter and pass the additional arguments to it. Here is an example:
Create(Calculate, 6284.57, 3);
}
}
Parallelism
Introduction
As you may know from elementary or high school, parallelization consists of having two separate objects, such as two lines, run in the same direction. This concept is also used in application programming where various operations or tasks independent of each other can be performed at the same time. The .NET Framework make this possible in a library named the Task Parallel Library or TPL.
Task parallelism in the .NET Framework is made possible through a class named Parallel:
public static class Parallel
Parallel is a static class defined in the System.Threading.Tasks namespace. The class contains just three methods that are each overloaded with various versions.
Looping
One of the methods of the Parallel class is named For. This method primarily functions like the for loop of the C# language. As the For() method is overloaded, the simplest version uses the following syntax:
public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int> body);
This is equivalent to the following formula of a for loop:
for(int i = fromInclusive, i < toExclusive, i++) { body }
This version supposes that the iteration will be based on counting small to medium integral values. If you want the counting to apply to large or very large incrementing values, you can use the following version of the method:
public static ParallelLoopResult For(long fromInclusive, long toExclusive, Action<long> body);
When a C# for loop runs, the compiler executes the body operation on the first value. When that operation ends, the compiler moves to the next number and executes the body operation again. The compiler continues that routine to the last value in the range. When a Parallel.For() method is called, instead of simply counting through the range of numbers between the fromInclusive and the toExclusive numbers, the compiler divides (or partitions) the jobs (or tasks) based on the number between those two extremes so that all operations can run at the same time instead of one after another.
Looping
Instead of executing tasks based on a range of values, the Parallel class provides an overloaded method named ForEach that is the equivalent to the C# foreach loop. The simple version of the Parallel.ForEach() method uses the following syntax:
public static ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> source, Action<TSource> body);
In most. Here is an example:
using
Instead. Here is an example:
using
If. Here are examples:
using
To.
Creating a Thread
Introduction
Multi-tasking:
To:
public
A thread:
This:
This. Here is an example:
using
In:
usi
This would produce:
Primary Operations on a Thread
The Apartment Area of a Thread
When:
public
Their syntaxes are:
public;
As
As. Here is an example of calling it:
using
In.
Suspending a Thread
For syntax:
public
With. Here is an example of calling this method:
using
This:
public
Here:
private
In:
using
The:
public
Based. Here is an example:
using
Terminating a Thread
As. Here is an example:
using
This would produce:
In:
using
This would produce:
method. Its syntax is:
This.
Characteristics of a Thread
The Name of a Thread
When:
This. Here is an example of using this property:
using
This would produce:
The Identifier of a Thread
As:
public
The Thread Has Started, Or Not
As:
public
If.
The Importance/Priority of a Thread
Not:
public
The:
using
The Current Thread
public
Here:
using
This would produce:
A Background Thread
All:
public
As:
using
This would produce:
The Status of a Thread
At:
public
Use.
Managing the Execution of a Thread
Passing an Object to a Thread
The. Its syntax is:
public
This:
public
Here is an example:
Thread
public
This. Here is an example:
using
Blocking a Thread
In the following syntax:
public
This the following syntaxes:
public
Both. Here are examples:
using
This would produce:
You:
using
using
This:
using
This would produce:
In:
using
Here is an example:
using
As:Can. Here is an example:
Can. Here is an example:
using
CanCan. Here is an example
using
Can.
Characteristics of Threads |
|
Managing the Execution of a Thread
Passing an Object to a Thread
public Thread(ParameterizedThreadStart start);
argument:
public delegate void ParameterizedThreadStart(object obj);
Here is an example of using this constructor:
syntax is:
public void Start(object parameter);
This means that, when calling the Thread.Start() method, pass your object as argument. Here is an example:
ParameterizedThreadStart tsLeftRightVehicle = new ParameterizedThreadStart(DrawLeftRightVehicle);
Thread thLeftRightVehicle = new Thread(tsLeftRightVehicle);
Blocking a Thread
The other two versions use the following syntaxes:
public bool Join(int ); public bool Join(TimeSpan timeout);
time.
Threading and Object-Oriented Programming
.
Practical Learning: Blocking a Thread
Exceptionally Handling a Thread
Introduction
.
try { // Normal thread operation(s) } catch(argument) { // Handling exception(s) }
Of course, you can include as many catch blocks as you judge necessary.
Aggregating the Execution of an Application
As mentioned in our introduction, a thread is a small program that contributes to the execution of a process (also called an application). Something inside the thread may cause it to behave badly. For example, an internal calculation may go wrong. One thread may interfer, or try to interfer, with the job that another thread is trying to accomplish. These types of problems may interrupt a process or make the result of an application inpredictable. To assist you with these types of problems, the .NET Framework provides the AggregateException class. This class includes many constructors with different goals.
The primary way to use the AggregateException exception is to pass it to the catch() clause. Here is an example:
using System; using System.Drawing; using System.Threading; using System.Windows.Forms; public class Exercise : System.Windows.Forms.Form { System.Windows.Forms.PictureBox pbxCanvas; private int xPosition; private int yPosition; private Image imgLRVehicle; private Image imgBackground; private System.Windows.Forms.Timer tmrDrawVehicle; public Exercise() { InitializeComponent(); } private void InitializeComponent() { pbxCanvas = new System.Windows.Forms.PictureBox(); pbxCanvas.Dock = DockStyle.Fill; pbxCanvas.Paint += new PaintEventHandler(pbxCanvasPaint); Controls.Add(pbxCanvas); tmrDrawVehicle = new System.Windows.Forms.Timer(); tmrDrawVehicle.Interval = 20; tmrDrawVehicle.Enabled = true; tmrDrawVehicle.Tick += new EventHandler(tmrDrawVehicleTick); Random rndNumber = new Random(); xPosition = rndNumber.Next(0, 1024); yPosition = 484; imgBackground = Image.FromFile("RoadMap1.jpg"); imgLRVehicle = Image.FromFile("LRVehicle1.png"); Text = "Traffic Monitoring"; StartPosition = FormStartPosition.CenterScreen; ClientSize = new System.Drawing.Size(1466, 924); } private void pbxCanvasPaint(object sender, PaintEventArgs e) { e.Graphics.DrawImage(imgBackground, 0, 0); e.Graphics.DrawImage(imgLRVehicle, xPosition, yPosition); } private void MoveVehicle() { if (xPosition < pbxCanvas.Width) xPosition++; else xPosition = -100; } private void tmrDrawVehicleTick(object sender, EventArgs e) { ThreadStart ts = new ThreadStart(MoveVehicle); Thread thVehicle = new Thread(ts); try { thVehicle.Start(); pbxCanvas.Invalidate(); } catch (AggregateException ae) { MessageBox.Show("Something went wrong and interferred with the application's " + "execution. Please report the error as follows." + Environment.NewLine + ae.Message, "Traffic Monitoring", MessageBoxButtons.OK, MessageBoxIcon.Information); } } public static int Main() { Application.EnableVisualStyles(); Application.Run(new Exercise()); return 0; } }
One of the constructors of the AggregateException class allows you to specify its message by passing a string to the constructor. Its syntax is:
public AggregateException(string message)
After initializing an AggregateException object with this constructor, its argument becomes the message of the exception. Here is an example of using this constructor:
AggregateException ae)
An Inner Exception
During its lifetime, a thread can throw many exceptions and exceptions from other threads can affect it. Problems or exceptions can involve threads from the same application as well as threads from other applications. Exceptions can also be caused by (child) threads created inside of (parent) threads. An inner exception is an exception that causes another exception. To support inner exceptions, the AggregateException class inherits a property named InnerException from the Exception class.
A Collection of Exceptions
Like one exception can cause another exception, many exceptions can cause an exception. The various exceptions that can cause an exception are treated as a collection. To let you get the collection of exceptions that have caused an exception, the AggregateException class includes a collection-based property named InnerExceptions:
public ReadOnlyCollection<Exception> InnerExceptions { get; }
To access each inner exception that caused an exception, you can use a foreach loop that will visit each item of the AggregateException object. To help you manage the exceptions that cause an exception, the AggregateException class includes various constructors that can be used to initialize an AggregateException object with a collection of exceptions related to its thread.
Handling Each Inner Exception
To assist you in handling an exception that is in the collection of the AggregateException exceptions, the AggregateException class includes a Boolean method named Handle. Its syntax is:
public void Handle(Func<Exception, bool> predicate)
This method takes an Exception object as argument and the function. The function returns a Boolean value that indicates whether the exception was actually handled. Here is an example of calling this method:
AggregateException ae) ae.Handle(PresentError);
Of course, you don't have to first define the function. You can implement it directly where it is needed.
When a Thread Aborts
As we saw in the previous lesson, one way to request that a thread be interrupted is to call the Thread.Abort() method. When this method is called, the operating system (OS) is asked to decide whether to terminate the operations of a thread. At that time, the OS throws an exception named ThreadAbortException. This class has only one member as a property named ExceptionState that is of type object:
public object ExceptionState { get; }
This property actually holds the information you should have passed to the Thread.Abort() method. Remember that the Thread.Abort() method doesn't actually terminate a thread. Therefore, neither call the method nor handle a ThreadAbortException exception in code that is continually executing, such as code that runs in a timer.
The Scope and Lifetime of an Object
Practical Learning: Adding a Method to an Interface
Practical Learning: Declaring a Variable of Interface Type
Practical Learning: Passing an Interface As Argument
Inheriting an Interface
implemented differently in different classes.
Practical Learning: Introducing Integers
Practical Learning: Introducing Loops
Practical Learning: Creating a While Loop
to the Main().
This would produce:
Finally, where you call this new method, pass the name of the method that is associated to the delegate. This can be done as follows. Here is an example:
Practical Learning: Checking for Super-Set
Practical Learning: Enumerating a Collection
the foreach operator that allows you to use a name for each member and omit the square brackets.
Practical Learning: Going for each Member of an Array
Practical Learning: Checking for Proper Sub-Set
Practical Learning: Introducing Streaming
Practical Learning: Introducing Operations on XML Elements
the SYSDATETIME() or the GETDATE() function. Here are examples:
INSERT INTO RepairOrders(CustomerName, CustomerPhone, RepairDate)
VALUES(N'Annette Berceau', N'301-988-4615', );
GO
INSERT INTO RepairOrders(CustomerPhone, CustomerName, RepairDate)
VALUES(N'(240) 601-3795', N'Paulino Santiago', );
GO
INSERT INTO RepairOrders(CustomerName, RepairDate, CustomerPhone)
VALUES(N'Alicia Katts', GETDATE(), N'(301) 527-3095');
GO
INSERT INTO RepairOrders(RepairDate, CustomerPhone, CustomerName)
VALUES(GETDATE(), N'703-927-4002', N'Bertrand Nguyen');
GO
Practical Learning: Ending the Lesson
SQL can be pronounced Sequel or S. Q. L. In our lessons, we will consider the Sequel pronunciation. For this reason, the abbreviation will always be considered as a word, which would result in “A SQL statement” instead of "An SQL statement". Also, we will regularly write, “The SQL” instead of “The SQL language, as the L already represents Language. |
Nesting a SELECT Statement
SELECT (SELECT (SELECT 1350.75));
GO
SELECT 24.85 AS ;
SELECT 24.85 AS 'Hourly Salary';
SELECT 'James Knight' As FullName, 20.48 AS Salary;
SELECT 'James Knight' As [Full Name], 20.48 AS [Hourly Salary];
When n' are cr
Introduction
The:.
The Number of Items in a Collection
. Here are examples:
use the != .
The : .
Data Analysis on Queries
Adding an Item
the
. Here is an example:
the :
The
named. Its syntax is:
A Parameterized Functionm
The Last Item of a Collection
. Here is an example:
Replacing an Item
Moving an Item
The . After
Swapping
Here is an example of how this can be done:
Starting a Graphical Application
Introduction to the .NET Framework
he variable. Here is an example:Youthat accesses the
Details on Creating a Form
The Controller of a Form
se, when creating the form, you can specify in what controller class some of the processing will be done.
The Action that Processes a Form
od that processes the form. Normally, this method is an action. Thereform, the method should an -type of object.
The Name of a Form
Inserting an Element
Getting an Item from a Collection
object:
The Height of a Form
the To specify the .
Delegates
Introduction
s.
Declaring a Delegate
Here is an example:
This would produce:
Practical Learning: Creating a Stream
A Helping Static Class
Introduction
rface, you must define each of the interface's method.
Introduction to the Forms of a View
This class is extended with various overloaded methods for different HTML objects. The methods are for a check box, To start, create and type
Practical Learning: Creating an Interface
Practical Learning: Writing to a Stream
.
The syntax of the and the System method is:
Here is an example: or the name of a class.
Adding First Child Element
Here is an example:
Practical Learning: Enumerating the Members of a Collection
Creating a Recursive Method
This would produce:
This would produce:
This would produce:
This would produce:
This would produce:
Practical Learning: Using the Anonymous Page Object
Controlling Access to a View
Introduction to Controllers
So ay the value of a member a for loop re-initialize the array by allocating new memory to it.
Practical Learning: Introducing Controllers
Checking for Nullity
Comparing an Object to Nullity
by the desired statment. Here is an example:
A Null Field
k to it. Here are examples:
The .
A Null Value for a Primitive Type
This would produce:
. Here is an example:
Introduction to Nullity
The Nullity of a Variable
.
A Null Object
Imagine you want to create an object from an interface or a class:
. Here are examples:
Here is an example:
This would produce:
This would produce:
This would produce:
A regular formula to use a read-write property is:
] =
The Path to a File
e. An example would be
Here is an example:I. Here are examples:
.
method. Here is an example:
method.l. Here are example:
. In the parentheses, pass the name of the control.
property and assign the desired integer to it.
Practical Learning: Setting the Left Posittion of a Control
The Top Position of a Control
. Toit.
Practical Learning: Specifying the Top Position of a Control
The Text of a Control
. he value of its
Practical Learning: Setting the Caption of a Label
The Width of a Control
.
Practical Learning: Specifying the Width of a Control
The Height of a Control
Practical Learning: Introducing Events
Practical Learning: Introducing Events
Converting a Value to a Natural Number
The basic formula to convert text to a decimal number is:The description is the same as for the integer.
Converting a Value to Text
This would produce:
This would produce:
AAA
A Delegate That Takes One of More Arguments
Here is an example:
ish the sections, the second one should be included in parentheses. Here is an example:
: Here are examples:
the.
Controlling the Type of Value of a Column
Checking Whether an Object IS Null
. Here is an example:This would produce
Practical Learning: Checking for Super-Set
This would produce:Consider the following list:
Notice that some records don't
have a value for some fields (such as the DirectorID property); they are empty. You can also directly pass an instance of the class in the square brackets of the object that holds the indexed property, as long as you
specify the object. Here is an example:
Practical Learning: Introducing Collection Iteration
Practical Learning: Executing a SQL Statement
Practical Learning: Applying an Enumerable List to a Combo Box
Using a View Bag
Practical Learning: Using a View Bag for a Combo Box
Introduction to the Collection Class
, IEnumerable<T>, IEnumerable, IList, ICollection, IReadOnlyList<T>, , T item)
Like its counter part the , the System.Collections.ObjectModel.Collection<T> class implements the System.Collections.Generic.ICollection<> interface. As a result, it has the functionality to add new items, to remove one or all items, to check the existence of an item, or to enumerate the collection. Like the System.Collections.Generic.List<> class, the System.Collections.ObjectModel.Collection<> class provides the ability to insert one item or a range or items in its collection. The System.Collections.ObjectModel.Collection<T> class provides a weSystem.Collections or the namespaces (normal/general lists, dictio classes for an object that is accessed by many threads at the same time. The System.Collections.Specialized namespace contains classea , System.Collections.ObjectModel, and . The System.Collections.Concurrent nanamed LinkedList. This is a huge class with various options. It provides all the methods and properties you need to add a first item, to add an item at the beginning of a list before the existing items, to add an item at the end of the list, to insert an item between two indicated items, to find any item, to get the item before a specified item, to get the item after the indicated item, to delete an item, and many other operations named InsertItem. Its syntax is:
Practical Learning: Enumerating a Collection
Practical Learning: Combining Various Disjunctions
Practical Learning: Going for each Member of an Array
Practical Learning: Checking for Proper Sub-Set
Editing or Updating Records
Introduction
You must specify the name of the involved table as the factor of our formula. The SET statement allows you to specify a new value, Expression, for the field under the ColumnName column.With this formula, you must specify the name of the involved table as the factor of our formula. The SET statement allows you to specify a new value, Expression, for the field under the ColumnName column. Imagine that, at one time, on a particular table, all records need to receive a new value under one particular column or certain columns. To update a record, the SQL provides the UPDATE keyword that is used to specify the table on which you want to maintain the record(s). The basic formula to use is:
UPDATE TableName SET ColumnName = Expression
Practical Learning: Introducing Record Maintenance
private void btnNewEmployee_Click(object sender, EventArgs e) { bool EmployeeFound = false; string strEmployeeNumber = ""; Employee empl = new Employee(); Random rndNumber = new Random(); // Create a random employee number. The user can change it if necessary strEmployeeNumber = rndNumber.Next(10, 99).ToString() + "-" + rndNumber.Next(100, 999).ToString() + "-" + rndNumber.Next(100, 999).ToString(); // Set some default values on the New Employee dialog box before the user opens it empl.txtEmployeeNumber.Text = strEmployeeNumber; empl.txtUserPassword.Text = "Password1"; // Open the New Employee dialog box. // Find out if the user clicked OK after using it. If that's the case, get ready to create a new employee record if (empl.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (string.IsNullOrEmpty(empl.txtEmployeeNumber.Text)) { MessageBox.Show("You must provide at least an employee number.", "FunDS - Fun Department Store", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } else { foreach (ListViewItem lviEmployee in lvwEmployees.Items) { if (empl.txtEmployeeNumber.Text == lviEmployee.SubItems[0].Text) EmployeeFound = true; } if (EmployeeFound == true) { MessageBox.Show("That employee number exists already.", "FunDS - Fun Department Store", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } else { using (SqlConnection scFunDS = new SqlConnection("Data Source=(local);" + "Database=FunDS17;" + "Integrated Security=Yes;")) { SqlCommand cmdSubCategories = new SqlCommand("INSERT INTO HumanResources.Employees " + "VALUES(N'" + empl.txtEmployeeNumber.Text + "', N'" + empl.txtFirstName.Text + "', N'" + empl.txtLastName.Text + "', N'" + empl.txtTitle.Text + "', " + double.Parse(empl.txtHourlySalary.Text) + ", N'" + empl.txtUsername.Text + "', N'" + empl.txtUserPassword.Text + "');", scFunDS); scFunDS.Open(); cmdSubCategories.ExecuteNonQuery(); } } } ShowEmployees(); } }
Control | Text | Name | Other Properties | ||
Button | OK | btnOK | DialogResult: OK | ||
Button | Cancel | btnCancel | DialogResult: Cancel |
(Name) | Text | TextAlign | Width |
colCategory | Category | 160 |
Text | Name | Other Properties | |||
ListView |
FullRowSelect: True GridLines: True View: Details |
||||
Button | New Category ... | btnNewCategory | |||
Button | Close | btnClose |
|
||||||||||||||||||||||||
|
(Name) | Text | TextAlign | Width |
colSubCategory | Sub-Category | 160 |
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
(Name) | Text | TextAlign | Width |
colReceiptNumber | Employee # | 70 | |
colFirstName | First Name | 70 | |
colLastName | Last Name | 70 | |
colTitle | Title | 140 | |
colHourlySalary | Salary | Right | 70 |
colUsername | Username | ||
colPassword | Password | 65 |
|
||||||||||||||||||||||||||||||||||||
|
|
|
|
Updating all Records
UPDATE = Expression
The WHERE operator allows you to specify how the particular record involved would be identified. It is very important, in most cases, that the criterion used be able to uniquely identify the record. In the above table, imagine that you ask the interpreter to change the released year to 1996 where the director of the video is Rob Reiner. The UPDATE statement would be written as follows:
UPDATE Videos SET YearReleased = 1996 WHERE Director = 'Rob Reiner';
Practical Learning: Updating all Records
Updating One or Some Records
In SQL, you must provide a way for the interpreter to locate the record. To do this, you would associate the WHERE operator in an UPDATE statement using the following formula:
UPDATE TableName SET ColumnName = Expression WHERE Condition(s)
The WHERE operator allows you to specify how the particular record involved would be identified. It is very important, in most cases, that the criterion used be able to uniquely identify the record. In the above table, imagine that you ask the interpreter to change the released year to 1996 where the director of the video is Rob Reiner. The UPDATE statement would be written as follows:
UPDATE Videos SET YearReleased = 1996 WHERE Director = 'Rob Reiner';
In the above table, there are at least two videos directed by Rob Reiner. When this statement is executed, all video records whose director is Rob Reiner would be changed, which would compromise existing records that did not need this change. Therefore, make sure your WHERE statement would isolate one particular record or only those that need to be updated. Here is an example used to change the name of the director of a particular video:
WHERE [Video Title] = N'The Distinguished Gentleman';",
cntVideos);
cntVideos.Open();
cmdVideos.ExecuteNonQuery();
MessageBox.Show("The director of 'The Distinguished Gentleman' " +
"Video Collection",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Practical Learning: Updating Some Records
private void btnDiscountRates_Click(object sender, EventArgs e) { using (SqlConnection cntFunDS = new SqlConnection("Data Source=(local);" + "Database='FunDS25';Integrated Security=True;")) { SqlCommand cmdStoreItems = new SqlCommand("UPDATE Inventory.StoreItems " + "SET DiscountRate = 0.10 WHERE DATEDIFF(d, DateEntered, SYSDATETIME()) > 30; " + "UPDATE Inventory.StoreItems " + "SET DiscountRate = 0.15 WHERE DATEDIFF(d, DateEntered, SYSDATETIME()) > 45; " + "UPDATE Inventory.StoreItems " + "SET DiscountRate = 0.30 WHERE DATEDIFF(d, DateEntered, SYSDATETIME()) > 60; " + "UPDATE Inventory.StoreItems " + "SET DiscountRate = 0.50 WHERE DATEDIFF(d, DateEntered, SYSDATETIME()) > 75; " + "UPDATE Inventory.StoreItems " + "SET DiscountRate = 0.75 WHERE DATEDIFF(d, DateEntered, SYSDATETIME()) > 90", cntFunDS); cntFunDS.Open(); cmdStoreItems.ExecuteNonQuery(); } using (SqlConnection cntFunDS = new SqlConnection("Data Source=(local);" + "Database='FunDS25';Integrated Security=True;")) { SqlCommand cmdStoreItems = new SqlCommand("UPDATE Inventory.StoreItems " + "SET DiscountAmount = FORMAT(UnitPrice * DiscountRate, N'F'); " + "UPDATE Inventory.StoreItems " + "SET MarkedPrice = FORMAT(UnitPrice - DiscountAmount, N'F');", cntFunDS); cntFunDS.Open(); cmdStoreItems.ExecuteNonQuery(); } ShowInventory(); }
Deleting Records
Deleting all Records
Using SQL, to clear a table of all records, use the DELETE operator with the following formula:
When this statement is executed, all records from the TableName factor would be removed from the table. Be careful when doing this because once the records have been deleted, you cannot get them back.
Instead of removing TableName all recordsNumber, to delete only the first n of a table, n use the following formula:
DELETE );
In the parentheses, enter the desired number of records. When the statement executes, the first n records of the table would be deleted. Here is an example:
To visually remove a record from a table, open the table in Table view, right-click the gray box of the record and click Delete. You can also first select the record and press Delete. You would receive a warning to confirm your intention.
To programmatically delete a record:
In SQL, to delete a record, use the WHERE operator. The formula to follow is:
TableName Condition(s)
The TableName factor is used to identify a table whose record(s) would be removed.
The Condition(s) factor allows you to identify a record or a group of records that carries a criterion. Once again, make sure you are precise in your criteria so you would not delete the wrong record(s). Here is an example used to remove a particular record from the table:
Practical Learning: Deleting Some Records
Conditionally Removing the First Records
Consider the following table:
By default, the DELETE expression acts on TableName WHERE Condition(s) all records of a table. As an alternative, you can ask the database engine to Number consider only the first n records of a table. The formula to do this is:
In the parentheses after Numberthe first Number of records. Any TableName WHERE Condition(s) record that falls in that condition would be deleted. Here is an example:
Outputting the Deleted Results
When some record(s) has(have) been deleted, the operation is performed behind the scenes and TableNameyou don't see the result. If you want to see a list of the records that were deleted, you can use the OUTPUT operator to display the result. To show the list Columnsof the records from a table that was completely emptied, you can use the following formula:
The OUTPUT INSERTED expression follows the description we have seen for the record update. Here is an example:
USE VideoCollection6; GO DELETE FROM Videos OUTPUT deleted.* GO
To show the list of the records that were deleted based on a condition, use the following formula:DELETE FROM Columns WHERE Condition(s)
USE VideoCollection6; GO DELETE FROM Videos OUTPUT deleted.* WHERE YearReleased IS NULL; GO---------------------------------------------
Practical Learning: Introducing Databases
Practical Learning: Creating a Database
Practical Learning: Creating a Database
Practical Learning: Opening a Query Window
the ToList() methodselect table select select
Practical Learning: Aligning the Content of a Text Box
creating the select IEnumerable interface is equipped with the ToList() methodThis method follows the same rules as its counterpart the ToArray() method except that you must declare a List> generic public static List<TSource> ( this source);for it. Here is an example:
the C#s .This would produce:
This would produce:This would produce:
This would produce:
Overview
Introduction to Creating a Helper
The primary formula to create a helper is:
lude code for the helper. Here is an example:
a variable of the class and use the period operator to access the helper. Here is an example:
Introduction to Parameters and Arguments
Introduction to the Parameters of a Helper
To
)
Calling a Helper that Uses a Parameter
. Here is an example:
A Helper With Many Parameters
. Here is an example:
The parameters can also be of different types. Here is an example of a helper that uses 3 parameters:
As mentioned earlier, you don't have to use the parameters in the body of the helper if you don't have use for it. Otherwise, in the body of the helper, you can use the parameters any appropriate way you want.
The Scope and Lifetime of a Variable
Introduction
The scope of a variable is the extent to which it is available to other members of a class. To manage this, a variable is said to have local or global scope.
A Global Variable
Helpers and Class
The Scope and Lifetime of an Object
Once this has been done, the object is ready to be used by any helper of the same class. As an alternative, you can declare the variable in the body of the class but initialize it in a helper of the class. Here is an example:
In the same way, you can create a helper that uses various parameters that are of type . Here is an example:
Practical Learning: Disposing of Components
Practical Learning: Creating a Helper
Practical Learning: Using Local Variables in a Helper
Practical Learning: Creating an Interface
Practical Learning: Using a Local Object
Practical Learning: Adding a Property to an Interface
Here is an example:
In the same way, you can add as many methods as you want. In every class or structure that implements the interface, you must define each of the interfaces method., ,
Practical Learning: Adding a Method to an Interface
When allocating memory for the object using the new operator, you must use a class that implements that interface. Here is an example:You can also declare the variable and allocate its memory on the same line. Here is an example:After that, you can use the object.
If you use any of these two techniques, you can access only the members of the interface. The non-interface members of the class would not be available. As a result, the following code would produce an error:
Practical Learning: Declaring a Variable of Interface Type
Practical Learning: Passing an Interface As Argument
Practical Learning: Returning an Interface
Inheriting an Interface
An interface can be derived from another interface (but an interface cannot derive from a class). Obviously the derived interface is supposed to add some behavior using methods and/or properties. Here is an example:
As you should know already that nothing is implemented in an interface, a member of the parent interface cannot be defined in a derived interface. Also, any class that needs the behavior(s) of the derived interface must implement all members of the derived interface and those of the parent interface(s). Here is an example:
Practical Learning: Introducing Integers
Practical Learning: Introducing Loops
Practical Learning: Creating a While Loop
Presenting a Character
As seen for the other types of variables, to make it possible to display a character to the console, the class is equipped with a version that takes a character as argument. Its syntax is:
Here is an example:
Console class provides the following version of the WriteLine() method:
);
Here are examples of calling this method:
Practical Learning: Overloading an Indexer
Main()'s Argument
Introduction
Main() function. In fact, a er looks for a function called . If it doesn't find it, it produces an error. If it finds it, it enters the Main().
Here are examples:
This would produce:
);
If you want the user to provide additional information when executing your program, you can take care of this in the Main() function. Consider the following code written in a file saved as Exercise.cs:
and press Enter. The program would then prompt you for the information it needs.
to the Main().
.
Here is an example:
Here is an example:
This would produce:
Here is an example:
v
This would produce:
Finally, where you call this new method, pass the name of the method that is associated to the delegate. This can be done as follows. Here is an example:
Finally, where you call this new method, pass the name of the method that is associated to the delegate. This can be done as follows. Here is an example:
Practical Learning: Grouping the Categories
Grouping Into a Variable
into contextual keyword through the following formula:
into GroupVariable ...;
The GroupVariable is the new factor in our formula. You specify it as a regular name of a variable. Here is an example:
into Categories
IGrouping. This means that you can access its Key property or you can access one of the methods that the interface gets from IEnumerable, and then use it as you see fit. Here is an example:
Before ending the LINQ statement, you must create either a group...by expression or a select statement that uses the into variable. Here is an example:
Enumerable.Contains(lstVideos[0])
This would produce:
selected or grouped...by
Exercise Exercise Catherine Engolo 42.50 20.48
Practical Learning: Creating an Empty Set
Opening a File
This would produce:
Information
CommandLine. Here is an example of accessing it:
. Here is an example:This would produce
Practical Learning: Checking for Super-Set
This would produce:Consider the following list:
Notice that some records dont have a value for some fields (such as the DirectorID property); they are empty. You can also directly pass an instance of the class in the square brackets of the object that holds the indexed property, as long as you specify the object. Here is an example:
Practical Learning: Introducing Collection Iteration
Action<string>
Practical Learning: Enumerating a Collection
Practical Learning: Combining Various Disjunctions
Chemistry08.App_Code.Element p = new Chemistry08.App_Code.Element() { ElementName = "Phosphorus", AtomicWeight = 30.973761998M, Symbol = "P", AtomicNumber = 15, Phase = Chemistry08.App_Code.Phase.Solid }; N o F Ne Na Mg Al Si p
Practical Learning: Combining Various Disjunctions
<form name="frmChemistry" method="post"> <table> <tr> <td class="left-col emphasize">Atomic Number:</td> <td><input type="text" name="txtAtomicNumber" value=@selected.AtomicNumber /></td> </tr> <tr> <td class="emphasize">Symbol:</td> <td><input type="text" name="txtSymbol" value=@selected.Symbol /></td> </tr> <tr> <td class="emphasize">Element Name:</td> <td><input type="text" name="txtElementName" value=@selected.ElementName /></td> </tr> <tr> <td class="emphasize">Atomic Weight:</td> <td><input type="text" name="" value=@selected.AtomicWeight /></td> </tr> <tr> <td class="emphasize">Phase:</td> <td><input type="text" name="" value=@selected.Phase /></td> </tr> </table> </form> }
: State
Looping Each Object
the foreach operator that allows you to use a name for each member and omit the square brackets.
Practical Learning: Going for each Member of an Array
Introduction to Collection-Based Controls
The Checked List Box
t. Here is an example:
ox button from the Common Controls section of the Toolbox. To programmatically create a checked list box, declare a variable of type CheckedListBox and initialize it appropriately. Here is an example:
This would produce:
The Checked List Box
This would produce:
Practical Learning: Checking for Proper Sub-Set
Practical Learning: Introducing Streaming
The Server Path to a File
. When you click OK, s .the a
Practical Learning: Creating a Stream
Delegates and Parameters
A Delegate that Uses a Parameter
is calledHere is an example of accessing the value of the above scenario in a webpage:
When creating a method that takes the delegate as parameter, you can also pass additional parameters as the same numbers and types used in the delegate. In the body of the method, you can call the delegated parameter and pass the additional arguments to it. Here is an example:
Practical Learning: Introducing operations on XML Elements
Practical Learning: Introducing Operations on XML Elements
private void btnClose_Click(object sender, EventArgs e) { Close(); }
Introduction to the SQL Connection
Data Entry and Functions
You can involve a function during data entry. For example, you can call a function that returns a value and assign that value to a column. You can first create your own function and use it, or you can use one of the built-in functions. Imagine you have a database named AutoRepairShop and it has a table used to create repair orders for customers:
CREATE TABLE RepairOrders ( RepairID int Identity(1,1) NOT NULL, CustomerName varchar(50), CustomerPhone varchar(20), RepairDate datetime2 ); GO
When performing data entry for this table, you can let the user enter the customer name and phone number. On the other hand, you can assist the user by programmatically entering the current date. To do this, you would call the SYSDATETIME() or the GETDATE() function. Here are examples:
INSERT INTO RepairOrders(CustomerName, CustomerPhone, RepairDate) VALUES(N'Annette Berceau', N'301-988-4615', GETDATE()); GO INSERT INTO RepairOrders(CustomerPhone, CustomerName, RepairDate) VALUES(N'(240) 601-3795', N'Paulino Santiago', GETDATE()); GO INSERT INTO RepairOrders(CustomerName, RepairDate, CustomerPhone) VALUES(N'Alicia Katts', GETDATE(), N'(301) 527-3095'); GO INSERT INTO RepairOrders(RepairDate, CustomerPhone, CustomerName) VALUES(GETDATE(), N'703-927-4002', N'Bertrand Nguyen'); GO
You can also involve the function in an operation, then use the result as the value to assign to a field. You can also call a function that takes one or more arguments; make sure you respect the rules of passing an argument to a function when calling it.
Other Features of Data Entry
Is RowGuid
This property allows you to specify that a column with the Identity property set to Yes is used as a ROWGUID column.
Topics on Creating Records
When you create a column that has an expression, the column doesn't have actual values. It is only a representative of values from other columns or constants. The column is referred to as a virtual column. Consider the following table:
The FullName only shows values that are from the FirstName and the LastName columns. This means that, unlike the FirstName and the LastName columns that have actual values, there is no real value in the FullName column. Transact-SQL allows you to actually store the value of the expression in the column. Storing the value in the column is referred to as persisting the value.To ask the database engine to store the value of the expression (as an actual value), when creating the column, add a flag named PERSISTED at the end of the column definition. Here is an example:
---------------------------------------------------ExecuteReader() method that is overloaded with two versions. The simplest version of this method uses the following syntax:Based on this, before using a data reader, you should first create a command that would specify how data would be acquired. Once the data is read, you can pass it to the data reader by assigning the result of a call to a SqlCommand.ExecuteReader() method to a SqlDataReader object.
Once data is supplied to the reader, you can access it, one value at a time, from top to bottom. To access data that the reader acquired, you can call its Read() method whose syntax is:
As mentioned already, the Read() method simply reads a value and moves on. When reading the values, as mentioned already, the data reader reads one value at a time and moves to the next.
---------------------------------------------------SQL can be pronounced Sequel or S. Q. L. In our lessons, we will consider the Sequel pronunciation. For this reason, the abbreviation will always be considered as a word, which would result in “A SQL statement” instead of "An SQL statement". Also, we will regularly write, “The SQL” instead of “The SQL language, as the L already represents Language. |
Microsoft's.
.
The SQL Interpreter
SQL's
, SQL Code
}
In this example, the SQL Code factor represents a SQL statement you would write and pass it as a string.
Executing a Statement
SQL Code command.ExecuteNonQuery(); connection.Close(); }
SQL Selection
Introduction to SQL Operators and Operands
key1=value1;key2=value2;key_n=value_n");
}
key1=value1;key2=value2;key_n=value_n";
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection();
connection.ConnectionString = strConnection;
}
property: the connectionString attribute of the add node in a web.config file. The operations are typically handled through a class named DataSet. DataSet
ss the necessary SQL code as the command text of the object:
private void btnDatabase_Click(object sender, EventArgs e) { SqlConnection connection = new SqlConnection("Data Source=(local);Integrated Security=yes"); SqlCommand command = new SqlCommand(
The primary piece of information about a database is its name. There are rules you must follow and suggestion you should observe:
Because of the flexibility of SQL, it can be difficult to maintain names in a database. Based on this, there are conventions we will use for our objects. In fact, we will adopt the rules used in C/C++, C#, Pascal, Java, and Visual Basic, etc. In our databases:
After creating an object whose name includes space, whenever you use that object, include its name between [ and ]. Examples are [Countries Statistics], [Global Survey], or [Date of Birth]. Even if you had created an object with a name that doesn't include space, when using that name, you can still include it in square brackets. Examples are [UnitedStations], [FullName], [DriversLicenseNumber], and [Country].
To assist you with creating and managing databases, including their objects, you use a set of language tools referred to as the Data Definition Language (DDL). This language is made of commands. For example, the primary command to create a database uses the following formula:
CREATE DNationalCensus.ldf') GO
Opening and Closing a Connection
Closing or Deleting a Connection
If you are wconnection. Inside of the curly brackets, you can do whatever you want. When the compiler reaches the closing curly bracket, it calls the SqlConnection.Close() method, which means you do not need to remember to close it.
Database Maintenance
Connecting to a Database
Once a database exists on the server, to use it, as we saw in the previous lesson, you must first establish a connection to it. We saw that, to programmatically connection to a Microsoft SQL Server database, you could use a SqlConnection variable. In the connection string, to specify the database, assign its name to the Database attribute. Here is an example:
Once you have established a connection, you can then open it and perform the desired actions:
SQL Code, connection); connection.Open(); command.ExecuteNonQuery(); connection.Close(); } }
Renaming a Database
Database maintenance consists of renaming one database or removing another. To change the name of a database, Transact-SQL provides sp_renamedb. (Notice that the name starts with sp_. This is called a stored procedure. We will learn how to create them. For now, trust that they work and do what they are supposed to do). The formula used would be:
EXEC sp_renamedb 'ExistingName', 'NewName'
The EXEC sp_renamedb expression is required. The ExistingName factor is the name of the database that you want to rename. The NewName factor is the name you want the database to have after renaming it.Here is an example of renaming a database:
EXEC sp_renamedb 'RentalCars', 'BethesdaCarRental GO
To rename a table in a C# code, pass the EXEC sp_renamedb code as string to a SqlCommand object and call the SqlCommand.ExecuteNonQuery() method.
Integers
SELECT Something
The
SELECT what-column(s)
Based on this, to use it, where it is needed, type followed by a number, a word, a string, or an expression. Here is an example:
SELECT 226.75;
Based on this definition, instead of just being a value, the thing on the right side of SELECT must be able to produce a value. SELECT can be used with more than one value. The values must be separated by commas. Here is an example:
SELECT 'Hourly Salary', 24.85
Nesting a SELECT Statement
Because we mentioned that the thing on the right side must produce a result, you can as well use another SELECT statement that itself evaluates to a result. To distinguish the SELECT sections, the second one should be included in parentheses. Here is an example:
SELECT (SELECT 448.25);
GO
When one SELECT statement is created after another, the second is referred to as nested.
SELECT (SELECT (SELECT 1350.75));
GO
default, the caption is "(No column name)". If you want to use your own caption, on the right side of an expression, type the AS keyword followed by the desired caption. The item on the right side of the AS keyword must be considered as one word. Here is an example:
SELECT 24.85 AS HourlySalary;
You can also include the item on the right side of AS in single-quotes. Here is an example:
SELECT 24.85 AS 'HourlySalary';
If the item on the right side of AS is in different words, you should include it in single-quotes or put them in inside of an opening square bracket [" and a closing square bracket "]". Here is an example:
SELECT 24.85 AS 'Hourly Salary';
If you create different sections, separated by commas, you can follow each with . Here is an example:
SELECT 'James Knight' As FullName, 20.48 AS Salary;
SELECT 'James Knight' As [Full Name], 20.48 AS [Hourly Salary];
Starting a Graphical Application
Introduction to the .NET Framework
Introduction to the Button Control
Overview
. Here is an example:
Introduction to the Array Class
Overview
To
rreferred to as a wheel.
The Mouse Up Message
ollows:
Introduction
When n' are cr
public abstract class DbConnection : Component, using (SqlConnection connection = new SqlConnection("Data Source=(local);Integrated Security=yes")IDisposable
Custom Message Implementation
same value. Here is an example:
Control's Construction and Destruction
. Here is an example:is:
Using a Visual C++/CLI Library
One
Checking a Class Member for Nullity
a valid value. Here is an example:
The
Accessing the Members of an Array
Declaring a Delegate
:
an example of a float array:
Fundamental Built-In Generic Interfaces
Introduction
interfaces.
This would produce:
This would produce:
Characteristics of
Introduction
The:
.
Fundamentals
Introduction
The Number of Items in a Collection
. Here are examples:
use the != .
Characteristics of Enumerable
A Read-Only Collection
The : ICollection<>.
Using Built-In Classes
classes.
Data Analysis on Queries
Adding an Item
the IList<> interface:
. Here is an example:
the IList<> interface:
Introduction
Inserting an Item
IList<interface provide a method named
The
Getting the Index of an Item
The
ICollection<> named. Its syntax is:
A Parameterized Functionm
Additional Operations on a Collection
Introduction
TheHere is an example:
The Last Item of a Collection
. Here is an example:
Replacing an Item
Moving an Item
The . After
Swapping
Here is an example of how this can be done:
Starting a Graphical Application
Introduction to the .NET Framework
he variable. Here is an example:Youthat accesses the
Details on Creating a Form
The Controller of a Form
When processing a form, you can write all of the code you need in the webpage. In other cases, some of the processing can be done in the controller class. In this case, when creating the form, you can specify in what controller class some of the processing will be done.
The Action that Processes a Form
method provides a version whose syntax is:This version takes two arguments. The second argument is the name of the controller that contains the code that processes the form. The first argument is a string that is the name of the method that processes the form. Normally, this method is an action. Thereform, the method should an -type of object.
The Name of a Form
BeginForm()IList< generic interface inherits. Its syntax is:
Inserting an Element
Getting an Item from a Collection
ViewBag object:
The Height of a Form
the To specify the .
Delegates
Introduction
s.
Declaring a Delegate
Here is an example:
This would produce:
Practical Learning: Creating a Stream
A Helping Static Class
Introduction
rface, you must define each of the interface's method.
Introduction to the Forms of a View
CheckBox() for a check box, RadioButton() for a radio button. The simplest version of each method takes only one argument. FoAs seen in previous lessons, there are two primary things you need to do in order to process the controls of a form. To start, create and INPUT control of type SUBMIT. Here is an that contains a contional statement that checks the value of an IsPost property:
Practical Learning: Creating an Interface
Practical Learning: Writing to a Stream
Checking the Existence of a Key
.
The syntax of the and the ContainsKey method is:
The syntax of the and the System method is:
::
Here is an example: or the name of a class.
X5. as on a null. Here is an example:
Adding First Child Element
Here is an example:
variable is null e isng the following formula:
Practical Learning: Enumerating the Members of a Collection
Creating a Recursive Method
This would produce:
This would produce:
This would produce:
This would produce:
This would produce:
Practical Learning: Using the Anonymous Page Object
Controlling Access to a View
Introduction to Controllers
So ay the value of a member a for loop re-initialize the array by allocating new memory to it.
Practical Learning: Introducing Controllers
Creating a Form in a View
Checking Whether an Object IS Null
formula:
. Here is an example:
Checking for Nullity
Comparing an Object to Nullity
ight operand. Here is an example:
mparing two objects. This operation can be performed =
access the member of a class. Here is an example:
Here is another version of the code:
The Null Coalescing Operator
he C# language provides the null coalescent operator represented as ?? (Two question marks). To apply it, type it after the condition followed by the desired statment. Here is an example:
House class:
A Null Field
k to it. Here are examples:
The .
A Null Value for a Primitive Type
This would produce:
This would produce:
. Here is an example:
Introduction to Nullity
The Nullity of a Variable
.
A Null Object
Imagine you want to create an object from an interface or a class:
. Here are examples:
Here is an example:
This would produce:
This would produce:
This would produce:
A regular formula to use a read-write property is:
on = new ();[index] = value
The Path to a File
e. An example would be
Here is an example:I. Here are examples:
.
Introduction to the Label Control
Overview of Labels
method. Here is an example:
method.l. Here are example:
. In the parentheses, pass the name of the control.
property and assign the desired integer to it.
Practical Learning: Setting the Left Posittion of a Control
The Top Position of a Control
. Toit.
Practical Learning: Specifying the Top Position of a Control
The Text of a Control
. he value of its
Practical Learning: Setting the Caption of a Label
The Width of a Control
.
Practical Learning: Specifying the Width of a Control
The Height of a Control
Practical Learning: Introducing Events
Practical Learning: Introducing Events
Converting a Value to a Natural Number
The basic formula to convert text to a decimal number is:The description is the same as for the integer.
Converting a Value to Text
This would produce:
This would produce:
A Delegate That Takes One of More Arguments
Here is an example:
the delegate.
A Delegate Passed as Argument
A delegate. Here is an example:
You. Here is an example:
Introduction to the Location
: Here are examples:
This version of the the value to the constant. would produce:
the.
}
On the other hand, to find out whether an object is not null, you can use the != operator with tkeyword as the right operand. Here is an example:
}
Checking Whether Two Objects Use the Same Reference
When you are dealing with result. Otherwise, the comparison is false types of objects in a section of code, you may be interested in comparing two objects. This operation can be performed using the
= object1
ed and the operation that must be performed proceeds.f the House class:
. Here is an example:This would produce
Practical Learning: Checking for Super-Set
This would produce:Consider the following list:
Notice that some records don't
have a value for some fields (such as the DirectorID property); they are empty. You can also directly pass an instance of the class in the square brackets of the object that holds the indexed property, as long as you
specify the object. Here is an example:
Practical Learning: Introducing Collection Iteration
Practical Learning: Enumerating a Collection
Practical Learning: Combining Various Disjunctions
C 7N 8o 9F 0Ne 1Na 2Mg 3Al 4Si
Practical Learning: Combining Various Disjunctions
Introduction to Collection-Based Controls
The Checked List Box
CheckedListBox button from the Common Controls section of the Toolbox. To programmatically create a checked list box, declare a variable of type CheckedListBox and initialize it appropriately. Here is an example:
Practical Learning: Checking for Proper Sub-Set
A Web Configuration File
Introduction
An ASP.NET MVC project (in fact any ASP.NET application) foreach operator that allows you to use a name for each member and omit the square brackets.a file named Web.config. This file is created at the root of the project (other folders or sections of a website may contain additional Web.config files). The Web.config file is an XML document that includes a section named connectionStrings. Inside that tag, create a child tag named Add. The Add tag must have three attributes named:
Based on this description, a connection string in the Web.config file can start as follows:
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit https://go.microsoft.com/fwlink/?LinkId=301880 --> <configuration> . . . No Change <connectionStrings> <add name="connection-string-name" connectionString="connection-string-details" providerName="System.Data.SqlClient" /> </connectionStrings> . . . No Change </configuration>
If you need to use many databases in your project, you can add a separate connection string for each. This means that you can create as many add nodes as you need in your Web.config document. This would be done as follows:
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit https://go.microsoft.com/fwlink/?LinkId=301880 --> <configuration> . . . No Change <connectionStrings> <add name="connection-string1-name" connectionString="connection-string1-details" providerName="System.Data.SqlClient" /> <add name="connection-string2-name" connectionString="connection-string2-details" providerName="System.Data.SqlClient" /> . . . <add name="connection-string_n-name" connectionString="connection-string_n-details" providerName="System.Data.SqlClient" /> . . . No Change </configuration>
As a result, the connectionStrings node is a parent to one or more add child nodes. As a result (sorry for the repetition), the connectionStrings node is a collection of add nodes. Each add node is also referred to as a section.
A Web Configuration Manager
To access a configuration file, you can use a ConfigurationManager object. You can also use a connection string builder.
The Source of Data
Remember that one of the characteristics of a connection string is the computer that holds the database you want to use. This is referred to as the data source. It can be identified as the Data Source. If you are working in an ASP.NET MVC project in Microsoft Visual Studio, the studio installed a small simple database server referred to as a local database and named LocalDB. To use it as your data source, specify the Data Source as (LocalDb)\MSSQLLocalDB.
The Path to the Database
To support the file name of a local database, the connection string has a factor named AttachDBFileName. To support the database file name, the SqlConnectionStringBuilder class is equipped with a property named AttachDBFilename:
public string AttachDBFilename { get; set; }
The path to the database must be assigned to this factor or property. Normally, you should create your database(s) in the App_Data folder. To indicate that this is where the database resides, assign |DataDirectory| to AttachDBFilename. This is followed by a backslash and the name of the database file with its .mdf extension.
@{
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection("Server=YellowCastle; ");
}
Practical Learning: Creating a Connetion String
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="csWaterDistribution"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\CommunityWater.mdf;Initial Catalog='CommunityWater';Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.6.1"/>
<httpRuntime targetFramework="4.6.1"/>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
</compilers>
</system.codedom>
</configuration>
Additional Attributes
There are various other attributes used in the connection string. They include Network Library (also called Net), Application Name, Workstation ID, Encrypt, Connection Timeout, Data Source, Packet Size, AttachDBFilename, Current Language, Persist Security Info.
After creating the connection string, when the application executes, the compiler would "scan" the string to validate each key=value section. If it finds an unknown Key, an unknown value, or an invalid combination of key=value, it would throw an ArgumentException exception and the connection cannot be established.
------------------------------------------------------Introduction to the SQL Connection
Data Entry and Functions
You can involve a function during data entry. For example, you can call a function that returns a value and assign that value to a column. You can first create your own function and use it, or you can use one of the built-in functions. Imagine you have a database named AutoRepairShop and it has a table used to create repair orders for customers:
CREATE TABLE RepairOrders ( RepairID int Identity(1,1) NOT NULL, CustomerName varchar(50), CustomerPhone varchar(20), RepairDate datetime2 ); GO
When performing data entry for this table, you can let the user enter the customer name and phone number. On the other hand, you can assist the user by programmatically entering the current date. To do this, you would call the SYSDATETIME() or the GETDATE() function. Here are examples:
INSERT INTO RepairOrders(CustomerName, CustomerPhone, RepairDate) VALUES(N'Annette Berceau', N'301-988-4615', GETDATE()); GO INSERT INTO RepairOrders(CustomerPhone, CustomerName, RepairDate) VALUES(N'(240) 601-3795', N'Paulino Santiago', GETDATE()); GO INSERT INTO RepairOrders(CustomerName, RepairDate, CustomerPhone) VALUES(N'Alicia Katts', GETDATE(), N'(301) 527-3095'); GO INSERT INTO RepairOrders(RepairDate, CustomerPhone, CustomerName) VALUES(GETDATE(), N'703-927-4002', N'Bertrand Nguyen'); GO
You can also involve the function in an operation, then use the result as the value to assign to a field. You can also call a function that takes one or more arguments; make sure you respect the rules of passing an argument to a function when calling it.
-------------------------------------------------------SQL Selection
Introduction to SQL Operators and Operands
key1=value1;key2=value2;key_n=value_n");
}
key1=value1;key2=value2;key_n=value_n";
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection();
connection.ConnectionString = strConnection;
}
property: the attribute of the . DataSet
ss the necessary SQL code as the command text of the object:
private void btnDatabase_Click(object sender, EventArgs e) { SqlConnection connection = new SqlConnection("Data Source=(local);Integrated Security=yes"); SqlCommand command = new SqlCommand(
The primary piece of information about a database is its name. There are rules you must follow and suggestion you should observe:
Because of the flexibility of SQL, it can be difficult to maintain names in a database. Based on this, there are conventions we will use for our objects. In fact, we will adopt the rules used in C/C++, C#, Pascal, Java, and Visual Basic, etc. In our databases:
After creating an object whose name includes space, whenever you use that object, include its name between [ and ]. Examples are [Countries Statistics], [Global Survey], or [Date of Birth]. Even if you had created an object with a name that doesn't include space, when using that name, you can still include it in square brackets. Examples are [UnitedStations], [FullName], [DriversLicenseNumber], and [Country].
CREATE a DATABASE
To assist you with creating and managing databases, including their objects, you use a set of language tools referred to as the Data Definition Language (DDL). This language is made of commands. For example, the primary command to create a database uses the following formula:
CREATE DNationalCensus.ldf') GO
Opening and Closing a Connection
Closing or Deleting a Connection
If you are wconnection. Inside of the curly brackets, you can do whatever you want. When the compiler reaches the closing curly bracket, it calls the SqlConnection.Close() method, which means you do not need to remember to close it.
Database Maintenance
Connecting to a Database
Once a database exists on the server, to use it, as we saw in the previous lesson, you must first establish a connection to it. We saw that, to programmatically connection to a Microsoft SQL Server database, you could use a SqlConnection variable. In the connection string, to specify the database, assign its name to the Database attribute. Here is an example:
Once you have established a connection, you can then open it and perform the desired actions:
SQL Code, connection); connection.Open(); command.ExecuteNonQuery(); connection.Close(); } }
Renaming a Database
Database maintenance consists of renaming one database or removing another. To change the name of a database, Transact-SQL provides sp_renamedb. (Notice that the name starts with sp_. This is called a stored procedure. We will learn how to create them. For now, trust that they work and do what they are supposed to do). The formula used would be:
EXEC sp_renamedb 'ExistingName', 'NewName'
The EXEC sp_renamedb expression is required. The ExistingName factor is the name of the database that you want to rename. The NewName factor is the name you want the database to have after renaming it.Here is an example of renaming a database:
EXEC sp_renamedb 'RentalCars', 'BethesdaCarRental GO
To rename a table in a C# code, pass the EXEC sp_renamedb code as string to a SqlCommand object and call the SqlCommand.ExecuteNonQuery() method.
SELECT Something
The
SELECT what-column(s)
Based on this, to use it, where it is needed, type followed by a number, a word, a string, or an expression. Here is an example:
SELECT 226.75;
Based on this definition, instead of just being a value, the thing on the right side of SELECT must be able to produce a value. SELECT can be used with more than one value. The values must be separated by commas. Here is an example:
SELECT 'Hourly Salary', 24.85
Nesting a SELECT Statement
Because we mentioned that the thing on the right side must produce a result, you can as well use another SELECT statement that itself evaluates to a result. To distinguish the SELECT sections, the second one should be included in parentheses. Here is an example:
SELECT (SELECT 448.25);
GO
When one SELECT statement is created after another, the second is referred to as nested.
SELECT (SELECT (SELECT 1350.75));
GO
default, the caption is "(No column name)". If you want to use your own caption, on the right side of an expression, type the AS keyword followed by the desired caption. The item on the right side of the AS keyword must be considered as one word. Here is an example:
SELECT 24.85 AS HourlySalary;
You can also include the item on the right side of AS in single-quotes. Here is an example:
SELECT 24.85 AS 'HourlySalary';
If the item on the right side of AS is in different words, you should include it in single-quotes or put them in inside of an opening square bracket "[" and a closing square bracket "]". Here is an example:
SELECT 24.85 AS 'Hourly Salary';
If you create different sections, separated by commas, you can follow each with . Here is an example:
SELECT 'James Knight' As FullName, 20.48 AS Salary;
SELECT 'James Knight' As [Full Name], 20.48 AS [Hourly Salary];--------------------------------------------------------------
Opening a Database
At any time, you must know what database you are currently using. To specify this, in the Solution Explorer of Microsoft SQL Server, right-click the name of the database and click Open.
Practical Learning: Opening a Query Window
CREATE SCHEMA Accessories;
GO
A Web Configuration File
Introduction
An ASP.NET MVC project (in fact any ASP.NET application) includes a file named Web.config. This file is created at the root of the project (other folders or sections of a website may contain additional Web.config files). The Web.config file is an XML document that includes a section named connectionStrings. Inside that tag, create a child tag named Add. The Add tag must have three attributes named:
Based on this description, a connection string in the Web.config file can start as follows:
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit https://go.microsoft.com/fwlink/?LinkId=301880 --> <configuration> . . . No Change <connectionStrings> <add name="connection-string-name" connectionString="connection-string-details" providerName="System.Data.SqlClient" /> </connectionStrings> . . . No Change </configuration>
If you need to use many databases in your project, you can add a separate connection string for each. This means that you can create as many add nodes as you need in your Web.config document. This would be done as follows:
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit https://go.microsoft.com/fwlink/?LinkId=301880 --> <configuration> . . . No Change <connectionStrings> <add name="connection-string1-name" connectionString="connection-string1-details" providerName="System.Data.SqlClient" /> <add name="connection-string2-name" connectionString="connection-string2-details" providerName="System.Data.SqlClient" /> . . . <add name="connection-string_n-name" connectionString="connection-string_n-details" providerName="System.Data.SqlClient" /> . . . No Change </configuration>
As a result, the connectionStrings node is a parent to one or more add child nodes. As a result (sorry for the repetition), the connectionStrings node is a collection of add nodes. Each add node is also referred to as a section.
A Web Configuration Manager
To access a configuration file, you can use a ConfigurationManager object. You can also use a connection string builder.
The Source of Data
Remember that one of the characteristics of a connection string is the computer that holds the database you want to use. This is referred to as the data source. It can be identified as the Data Source. If you are working in an ASP.NET MVC project in Microsoft Visual Studio, the studio installed a small simple database server referred to as a local database and named LocalDB. To use it as your data source, specify the Data Source as (LocalDb)\MSSQLLocalDB.
The Path to the Database
To support the file name of a local database, the connection string has a factor named AttachDBFileName. To support the database file name, the SqlConnectionStringBuilder class is equipped with a property named AttachDBFilename:
public string AttachDBFilename { get; set; }
AttachDBFilename. This is followed by a backslash and the name of the database file with its .mdf extension.
Practical Learning: Creating a Connetion String
Creating a Database
Introduction
key=value section key=value, it would throw an ArgumentException exception and the connection cannot be established.
Code First
orer of Microsoft Visual Studio. -> New Item...In the left frame of the Add New Item dialog box, click Data. In the middle frame, click SQL Server Database:
Practical Learning: Creating a Database
Practical Learning: Ending the Lesson
Opening a Database
At any time, you must know what database you are Network Library (also called Net), Application Name, Workstation ID, Encrypt, Connection Timeout, Data Source, Packet Size, AttachDBFilename, Current Language, Persist Security Info.using. To specify this, in the Solution Explorer of Microsoft SQL Server, right-click the name of the database and click Open.
Practical Learning: Opening a Query Window
The Scope and Lifetime of an Object
Practical Learning: Declaring a Variable of Interface Type
Practical Learning: Passing an Interface As Argument
Inheriting an Interface
implemented differently in different classes.
Practical Learning: Introducing Integers
Practical Learning: Introducing Loops
Practical Learning: Creating a While Loop
Here is an example:This would produce:
Here is an example:
This would produce:
Finally, where you call this new method, pass the name of the method that is associated to the delegate. This can be done as follows. Here is an example:
Practical Learning: Checking for Super-Set
Practical Learning: Enumerating a Collection
the foreach operator that allows you to use a name for each member and omit the square brackets.
Practical Learning: Going for each Member of an Array
Practical Learning: Checking for Proper Sub-Set
Practical Learning: Introducing Streaming
Practical Learning: Introducing Operations on XML Elements
the SYSDATETIME() or the GETDATE() function. Here are examples:
INSERT INTO RepairOrders(CustomerName, CustomerPhone, RepairDate)
VALUES(N'Annette Berceau', N'301-988-4615', );
GO
INSERT INTO RepairOrders(CustomerPhone, CustomerName, RepairDate)
VALUES(N'(240) 601-3795', N'Paulino Santiago', );
GO
INSERT INTO RepairOrders(CustomerName, RepairDate, CustomerPhone)
VALUES(N'Alicia Katts', GETDATE(), N'(301) 527-3095');
GO
INSERT INTO RepairOrders(RepairDate, CustomerPhone, CustomerName)
VALUES(GETDATE(), N'703-927-4002', N'Bertrand Nguyen');
GO
Practical Learning: Ending the Lesson
SQL can be pronounced Sequel or S. Q. L. In our lessons, we will consider the Sequel pronunciation. For this reason, the abbreviation will always be considered as a word, which would result in “A SQL statement” instead of "An SQL statement". Also, we will regularly write, “The SQL” instead of “The SQL language, as the L already represents Language. |
Nesting a SELECT Statement
SELECT (SELECT (SELECT 1350.75));
GO
SELECT 24.85 AS ;
SELECT 24.85 AS 'Hourly Salary';
SELECT 'James Knight' As FullName, 20.48 AS Salary;
SELECT 'James Knight' As [Full Name], 20.48 AS [Hourly Salary];
When n' are cr
Introduction
The:
.
The Number of Items in a Collection
. Here are examples:
use the != .
The : .
Adding an Item
the
. Here is an example:
the :
The
named. Its syntax is:
The Last Item of a Collection
. Here is an example:
Moving an Item
The . After
Swapping
he variable. Here is an example:Youthat accesses the
Details on Creating a Form
The Controller of a Form
se, when creating the form, you can specify in what controller class some of the processing will be done.
The Action that Processes a Form
od that processes the form. Normally, this method is an action. Thereform, the method should an -type of object.
The Name of a Form
Inserting an Element
Getting an Item from a Collection
object:
The Height of a Form
the To specify the .
Delegates
Introduction
s.
Declaring a Delegate
This would produce:
Practical Learning: Creating a Stream
Introduction to the Forms of a View
This class is extended with various overloaded methods for different HTML objects. The methods are for a check box, To start, create and type
Practical Learning: Creating an Interface
Practical Learning: Writing to a Stream
.
Practical Learning: Enumerating the Members of a Collection
Creating a Recursive Method
This would produce:
This would produce:
This would produce:
This would produce:
This would produce:
Practical Learning: Using the Anonymous Page Object
Controlling Access to a View
Introduction to Controllers
So ay the value of a member a for loop re-initialize the array by allocating new memory to it.
Practical Learning: Introducing Controllers
Checking for Nullity
Comparing an Object to Nullity
by the desired statment. Here is an example:
A Null Field
The .
This would produce:
. Here is an example:
Introduction to Nullity
The Nullity of a Variable
.
A Null Object
Imagine you want to create an object from an interface or a class:
. Here are examples:
Here is an example:
This would produce:
This would produce:
This would produce:
A regular formula to use a read-write property is:
] =
Here is an example:I. Here are examples:
.
method. Here is an example:method.l. Here are example:
. In the parentheses, pass the name of the control.
property and assign the desired integer to it.
Practical Learning: Setting the Left Posittion of a Control
The Top Position of a Control
. Toit.
Practical Learning: Specifying the Top Position of a Control
The Text of a Control
. he value of its
Practical Learning: Setting the Caption of a Label
The Width of a Control
.
Practical Learning: Specifying the Width of a Control
The Height of a Control
Practical Learning: Introducing Events
Practical Learning: Introducing Events
Converting a Value to a Natural Number
The basic formula to convert text to a decimal number is:The description is the same as for the integer.
Converting a Value to Text
This would produce:
This would produce:
AAA
A Delegate That Takes One of More Arguments
Here is an example:
ish the sections, the second one should be included in parentheses. Here is an example:
: Here are examples:
the.
Controlling the Type of Value of a Column
Checking Whether an Object IS Null
. Here is an example:This would produce
Practical Learning: Checking for Super-Set
This would produce:Consider the following list:
Notice that some records don't
have a value for some fields (such as the DirectorID property); they are empty. You can also directly pass an instance of the class in the square brackets of the object that holds the indexed property, as long as you
specify the object. Here is an example:
Practical Learning: Introducing Collection Iteration
Practical Learning: Applying an Enumerable List to a Combo Box
Using a View Bag
Practical Learning: Using a View Bag for a Combo Box
Introduction to the Collection Class
IReadOnlyList<T>, , T item)
Like its counter part the , the System.Collections.ObjectModel.Collection<T> class implements the System.Collections.Generic.ICollection<> interface. As a result, it has the functionality to add new items, to remove one or all items, to check the existence of an item, or to enumerate the collection. Like the System.Collections.Generic.List<> class, the System.Collections.ObjectModel.Collection<> class provides the ability to insert one item or a range or items in its collection. The System.Collections.ObjectModel.Collection<T> class provides a we or the System.Collections.Generic namespaces (normal/general lists, dictio classes for an object that is accessed by many threads at the same time. The namespace contains classea , , and . The System.Collections.Concurrent nanamed LinkedList. This is a huge class with various options. It provides all the methods and properties you need to add a first item, to add an item at the beginning of a list before the existing items, to add an item at the end of the list, to insert an item between two indicated items, to find any item, to get the item before a specified item, to get the item after the indicated item, to delete an item, and many other operations named InsertItem. Its syntax is:
Practical Learning: Enumerating a Collection
Practical Learning: Combining Various Disjunctions
Practical Learning: Going for each Member of an Array
Practical Learning: Checking for Proper Sub-Set
Editing or Updating Records
Introduction
You must specify the name of the involved table as the factor of our formula. The statement allows you to specify a new value, , for the field under the ColumnName column.With this formula, you must specify the name of the involved table as the factor of our formula. The SET statement allows you to specify a new value, Expression, for the field under the column. Imagine that, at one time, on a particular table, all records need to receive a new value under one particular column or certain columns. To update a record, the SQL provides the UPDATE keyword that is used to specify the table on which you want to maintain the record(s). The basic formula to use is:
UPDATE TableName SET ColumnName = Expression
Practical Learning: Introducing Record Maintenance
Control | Text | Name | Other Properties | ||
Button | OK | btnOK | DialogResult: OK | ||
Button | Cancel | btnCancel | DialogResult: Cancel |
(Name) | Text | TextAlign | Width |
colCategory | Category | 160 |
Text | Name | Other Properties | |||
ListView | FullRowSelect: True GridLines: True |
||||
Button | New Category ... | btnNewCategory | |||
Button | Close | btnClose |
|
Control | Text | Name | Other Properties | |
Label | Sub-Category: | |||
TextBox | txtSubCategory | Modifiers: Public | ||
Button | OK | btnOK | DialogResult: OK | |
Button | Cancel | btnCancel | DialogResult: Cancel |
(Name) | Text | TextAlign | Width |
colSubCategory | Sub-Category | 160 |
Control | Name | Other Properties | |||
ListView |
lvwEmployees |
FullRowSelect: True GridLines: True View: Details |
|||
Button | New Sub-Category ... | btnNewSubCategory | |||
Button | Close | btnClose |
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
(Name) | Text | TextAlign | Width |
colReceiptNumber | Employee # | 70 | |
colFirstName | First Name | 70 | |
colLastName | Last Name | 70 | |
colTitle | Title | 140 | |
colHourlySalary | Salary | Right | 70 |
colUsername | Username | ||
colPassword | Password | 65 |
|
||||||||||||||||||||||||||||||||||||
|
|
|
(Name) | Text | TextAlign | Width |
colSoldItemID | SI ID | 40 | |
colReceiptNumber | Receipt # | Center | |
colDateSold | Date Sold | Center | 75 |
colItemNumber | Item # | Center | |
colManufacturer | Manufacturer | 130 | |
colCategory | Category | 70 | |
colSubCategory | Sub-Category | 80 | |
colItemName | Item Name | 300 | |
colItemSize | Size | 80 | |
colUnitPrice | Unit Price | Right | |
colDiscountRate | Disc Rate | Right | 80 |
colDiscountAmount | Disc Amt | Right | 80 |
colSalePrice | Sale Price | Right |
|
(Name) | Text | TextAlign | Width |
colSoldItemID | SI ID | 40 | |
colReceiptNumber | Receipt # | Center | |
colDateSold | Date Sold | Center | 75 |
colItemNumber | Item # | Center | |
colManufacturer | Manufacturer | 130 | |
colCategory | Category | 70 | |
colSubCategory | Sub-Category | 80 | |
colItemName | Item Name | 300 | |
colItemSize | Size | 80 | |
colUnitPrice | Unit Price | Right | |
colDaysInStore | Days in Store | Right | 80 |
colDateRemovedFromStore | Date Removed From Store | Center | 140 |
Receipt #: | ||||
TextBox | txtReceiptNumber | |||
Label | Item # to Remove: | |||
TextBox | txtItemNumberRemove | |||
Button | Remove | btnRemoveItem | ||
Label | Order Total: | |||
TextBox | txtOrderTotal | Text: 0.00 TextAlign: Right |
||
Label | Tendered: | |||
TextBox | txtAmountTendered | Text: 0.00 TextAlign: Right |
||
Label | Processed By: | |||
TextBox | txtEmployeeNumber | |||
TextBox | txtEmployeeName | |||
Label | Change: | |||
TextBox | txtChange | |||
DateTimePicker | dtpSaleDate | |||
DateTimePicker | dtpSaleTime | Format: Time | ||
Button | btnReset | |||
Button | btnSubmit | |||
Button | btnClose |
Updating all Records
UPDATE = Expression
The WHERE operator allows you to specify how the particular record involved would be identified. It is very important, in most cases, that the criterion used be able to uniquely identify the record. In the above table, imagine that you ask the interpreter to change the released year to 1996 where the director of the video is Rob Reiner. The UPDATE statement would be written as follows:
UPDATE
Practical Learning: Updating all Records
Updating One or Some Records
Video Title | Director | © Year | Length | Rating |
A Few Good Men | Rob Reiner | 138 Minutes | R | |
The Silence of the Lambs | Jonathan Demme | 1991 | 118 Minutes | |
The Distinguished Gentleman | James Groeling | R | ||
The Lady Killers | Joel Coen & Ethan Coen | 104 Minutes | ||
Ghosts of Mississippi | Rob Reiner | 130 Minutes |
WHERE in an UPDATE
UPDATE TableName SET ColumnName = Expression WHERE Condition(s)
The WHERE UPDATE statement would be written as follows:
WHERE
Practical Learning: Updating Some Records
Deleting Records
Deleting all Records
Using SQL, to clear a table of all records, use the DELETE operator with the following formula:When this statement is executed, all records from the TableName factor would be removed from the table. Be careful when doing this because once the records have been deleted, you cannot get them back.
Instead of removing TableName all records, to delete only the first n of a table, n use the following formula:
In the parentheses, enter the desired number of records. When the statement executes, the first n records of the table would be deleted. Here is an example:
To visually remove a record from a table, open the table in Table view, right-click the gray box of the record and click Delete. You can also first select the record and press Delete. You would receive a warning to confirm your intention.
To programmatically delete a record:
In SQL, to delete a record, use the WHERE operator. The formula to follow is:
TableName Condition(s)
The TableName factor is used to identify a table whose record(s) would be removed.
The Condition(s) factor allows you to identify a record or a group of records that carries a criterion. Once again, make sure you are precise in your criteria so you would not delete the wrong record(s). Here is an example used to remove a particular record from the table:
Practical Learning: Deleting Some Records
TableName WHERE Condition(s) Numberfirst n records of a table. The formula to do this is:
In the parentheses after Numberthe first Number of records. Any TableName WHERE Condition(s) record that falls in that condition would be deleted. Here is an example:
Outputting the Deleted Results
TableName OUTPUTColumnsof the records from a table that was completely emptied, you can use the following formula:
The OUTPUT INSERTED expression follows the description we have seen for the record update. Here is an example:
To show the list of the records that were deleted based on a condition, use the following formula:DELETE FROM Columns WHERE Condition(s)
Here is an example:
USE VideoCollection6; GO DELETE FROM Videos OUTPUT deleted.* WHERE YearReleased IS NULL; GO
Practical Learning: Introducing Databases
Practical Learning: Creating a Database
Practical Learning: Creating a Database
Practical Learning: Opening a Query Window
the ToList() methodselect table select select
creating the generic public static List<TSource> ( this source);for it. Here is an example:
Introduction to Parameters and Arguments
Introduction to the Parameters of a Helper
Helpers and Class
The Scope and Lifetime of an Object
Practical Learning: Disposing of Components
Practical Learning: Creating a Helper
Practical Learning: Using Local Variables in a Helper
Practical Learning: Creating an Interface
Practical Learning: Using a Local Object
Practical Learning: Adding a Property to an Interface
Practical Learning: Adding a Method to an Interface
Practical Learning: Declaring a Variable of Interface Type
Practical Learning: Passing an Interface As Argument
Practical Learning: Returning an Interface
Practical Learning: Introducing Integers
Practical Learning: Introducing Loops
Practical Learning: Creating a While Loop
Presenting a Character
As seen for the other types of variables, to make it possible to display a character to the console, the class is equipped with a version that takes a character as argument. Its syntax is:
This would produce:
Console class provides the following version of the WriteLine() method:
);
Here are examples of calling this method:
Practical Learning: Overloading an Indexer
Main()'s Argument
Introduction
Main() function. In fact, a er looks for a function called . If it doesn't find it, it produces an error. If it finds it, it enters the Main().
Here are examples:
This would produce:
If you want the user to provide additional information when executing your program, you can take care of this in the Main() function. Consider the following code written in a file saved as Exercise.cs:
to the Main().
.
v
Finally, where you call this new method, pass the name of the method that is associated to the delegate. This can be done as follows. Here is an example:
Practical Learning: Grouping the Categories
into contextual keyword through the following formula:
into GroupVariable ...;
The GroupVariable is the new factor in our formula. You specify it as a regular name of a variable. Here is an example:
IGroupingits Key property or you can access one of the methods that the interface gets from IEnumerable, and then use it as you see fit. Here is an example:
Before ending the LINQ statement, you must create either a group...by expression or a select statement that uses the into variable. Here is an example:
Enumerable.Contains(lstVideos[0])
This would produce:
grouped...byExercise Exercise Catherine Engolo 42.50 20.48
Practical Learning: Creating an Empty Set
This would produce:
CommandLine. Here is an example of accessing it:
Practical Learning: Checking for Super-Set
This would produce:Consider the following list:
. Here is an example:
Practical Learning: Introducing Collection Iteration
Action<string>
Practical Learning: Enumerating a Collection
Practical Learning: Combining Various Disjunctions
Chemistry08.App_Code.Element p = new Chemistry08.App_Code.Element() { ElementName = "Phosphorus", AtomicWeight = 30.973761998M, Symbol = "P", AtomicNumber = 15, Phase = Chemistry08.App_Code.Phase.Solid }; p
Practical Learning: Combining Various Disjunctions
: State
Looping Each Object
the foreach operator that allows you to use a name for each member and omit the square brackets.
Practical Learning: Going for each Member of an Array
The Checked List Box
ox button from the Common Controls section of the Toolbox. To programmatically create a checked list box, declare a variable of type CheckedListBox and initialize it appropriately. Here is an example:
This would produce:
This would produce:
Practical Learning: Checking for Proper Sub-Set
Practical Learning: Introducing Streaming
Practical Learning: Creating a Stream
Delegates and Parameters
A Delegate that Uses a Parameter
is calledHere is an example of accessing the value of the above scenario in a webpage:
Practical Learning: Introducing operations on XML Elements
Practical Learning: Introducing Operations on XML Elements
Introduction to the SQL Connection
Data Entry and Functions
You
SYSDATETIME() or the GETDATE() function. Here are examples:
it.
Other Features of Data Entry
Is RowGuid
Identity property set to Yes is used as a ROWGUID column.
Topics on Creating Records
the following table:
The FullName only shows values that are from the FirstName and the LastName columns. This means that, unlike the FirstName and the LastName columns that have actual values, there is no real value in the FullName column. Transact-SQL allows you to actually store the value of the expression in the column. Storing the value in the column is referred to as persisting the value.To ask the database engine to store the value of the expression (as an actual value), when creating the column, add a flag named PERSISTED at the end of the column definition. Here is an example:
the SqlCommand class is equipped with the ExecuteReader() method that is overloaded with two versions. The simplest version of this method uses the following syntax:Based on this, before using a data reader, you should first create a command that would specify how data would be acquired. Once the data is read, you can pass it to the data reader by assigning the result of a call to a SqlCommand.ExecuteReader() method to a SqlDataReader object.
Using a SQL Data Reader
Read() method whose syntax is:
As mentioned already, the Read() method simply reads a value and moves on. When reading the values, as mentioned already, the data reader reads one value at a time and moves to the next.
SQL |
Microsoft's.
SQL's
Executing a Statement
SQL Selection
Introduction to SQL Operators and Operands
";
property: the connectionString attribute of the add node in ");akey1=value1;key2=value2;key_n=value_n web.config file. The operations are typically handled through a class named DataSet. DataSet
ss the necessary SQL code as the command text of the object:
The primary piece of information about a database is its name. There are rules you must follow and suggestion you should observe:
Because of the flexibility of SQL, it can be difficult to maintain names in a database. Based on this, there are conventions we will use for our objects. In fact, we will adopt the rules used in C/C++, C#, Pascal, Java, and Visual Basic, etc. In our databases:
After creating an object whose name includes space, whenever you use that object, include its name between [ and ]. Examples are [Countries Statistics], [Global Survey], or [Date of Birth]. Even if you had created an object with a name that doesn't include space, when using that name, you can still include it in square brackets. Examples are [UnitedStations], [FullName], [DriversLicenseNumber], and [Country].
formula:
Opening and Closing a Connection
Closing or Deleting a Connection
If you are wconnection. Inside of the curly brackets, you can do whatever you want. When the compiler reaches the closing curly bracket, it calls the SqlConnection.Close() method, which means you do not need to remember to close it.
Database Maintenance
Connecting to a Database
SqlConnection. Here is an example:
Once you have established a connection, you can then open it and perform the desired actions:
SQL
Renaming a Database
sp_renamedb.
EXEC sp_renamedb 'ExistingName', 'NewName'
The EXEC sp_renamedb expression is required. The ExistingName factor is the name of the database that you want to rename. The NewName factor is the name you want the database to have after renaming it.Here is an example of renaming a database:
EXEC sp_renamedb 'RentalCars', 'BethesdaCarRental GO
To rename a table in a C# code, pass the EXEC sp_renamedb code as string to a SqlCommand object and call the SqlCommand.ExecuteNonQuery() method.
SELECT
Nesting a SELECT Statement
SELECT. Here is an example:
SELECT 24.85 AS 'Hourly Salary';
. Here is an example:
SELECT 'James Knight' As FullName, 20.48 AS Salary;
SELECT 'James Knight' As [Full Name], 20.48 AS [Hourly Salary];
Starting a Graphical Application
Introduction to the .NET Framework
Here is an example:
Introduction to the Button Control
Overview
. Here is an example:
Introduction to the Array Class
Overview
To
ollows:
Introduction
When n' are cr
Custom Message Implementation
same value. Here is an example:
Control's Construction and Destruction
. Here is an example:is:
Using a Visual C++/CLI Library
One
Checking a Class Member for Nullity
The
Accessing the Members of an Array
Declaring a Delegate
:
an example of a float array:
Fundamental Built-In Generic Interfaces
Introduction
interfaces.
This would produce:
Characteristics of
Introduction
The:
.
Fundamentals
Introduction
The Number of Items in a Collection
. Here are examples:
use the != .
Characteristics of Enumerable
A Read-Only Collection
The : .
Using Built-In Classes
classes.
Data Analysis on Queries
Adding an Item
the IList<> interface:
. Here is an example:
the IList<> interface:
Introduction
Inserting an Item
IList<interface provide a method named
Getting the Index of an Item
The
ICollection<> named. Its syntax is:
A Parameterized Functionm
Introduction
TheHere is an example:
The Last Item of a Collection
. Here is an example:
Replacing an Item
The
Moving an Item
Swapping
Here is an example of how this can be done:
Starting a Graphical Application
Introduction to the .NET Framework
he variable. Here is an example:Youthat accesses the
Details on Creating a Form
The Controller of a Form
done.
The Name of a Form
IList< generic interface inherits. Its syntax is:
Inserting an Element
Getting an Item from a Collection
object:
The Height of a Form
the To specify the .
Delegates
Introduction
s.
Declaring a Delegate
Here is an example:
Practical Learning: Creating a Stream
A Helping Static Class
Introduction
rface, you must define each of the interface's method.
This WebPage class.To let you add a webcontrol to a form, the HtmlHelper class is extended with various overloaded methods for different HTML objects. The methods are TextBox() for a text box, CheckBox() for a check box, RadioButton() for a radio button. The simplest version of each method takes only one argument. FoAs seen in previous lessons, there are two primary things you need to do in order to process the controls of a form. To start, create and INPUT control of type SUBMIT. Here is an that contains a contional statement that checks the value of an IsPost property:
Practical Learning: Creating an Interface
Practical Learning: Writing to a Stream
is:
Here is an example: or the name of a class.
X5. Here is an example:
Adding First Child Element
Here is an example:
isng the following formula:
Practical Learning: Enumerating the Members of a Collection
Creating a Recursive Method
This would produce:
This would produce:
This would produce:
This would produce:
This would produce:
Practical Learning: Using the Anonymous Page Object
Introduction to Controllers
it.
Practical Learning: Introducing Controllers
Creating a Form in a View
Checking Whether an Object IS Null
formula:
Checking for Nullity
Comparing an Object to Nullity
ight operand. Here is an example:mparing
access the member of a class. Here is an example:
. Here is an example:
House class:
A Null Field
k to it. Here are examples:
The .
A Null Value for a Primitive Type
This would produce:
This would produce:
. Here is an example:
Introduction to Nullity
The Nullity of a Variable
.
A Null Object
Imagine you want to create an object from an interface or a class:
. Here are examples:
Here is an example:
This would produce:
This would produce:
This would produce:
A regular formula to use a read-write property is:
on = new ();[index] = value
The Path to a File
e. An example would be
Here is an example:I. Here are examples:
.
Introduction to the Label Control
Overview of Labels
method. Here is an example:
method.l. Here are example:
. In the parentheses, pass the name of the control.
property and assign the desired integer to it.
Practical Learning: Setting the Left Posittion of a Control
The Top Position of a Control
. Toit.
Practical Learning: Specifying the Top Position of a Control
The Text of a Control
. he value of its
Practical Learning: Setting the Caption of a Label
The Width of a Control
.
Practical Learning: Specifying the Width of a Control
The Height of a Control
Practical Learning: Introducing Events
This would produce:
AAA
A Delegate That Takes One of More Arguments
the delegate.
A delegate. Here is an example:
You. Here is an example:
Introduction to the Location
This version of the the value to the constant. would produce:
the.
}
. Here is an example:
}
Checking Whether Two Objects Use the Same Reference
false
= object1
ed and the operation that must be performed proceeds.f the House class:
. Here is an example:This would produce
Practical Learning: Checking for Super-Set
Notice that some records don't. Here is an example:
Practical Learning: Introducing Collection Iteration
Practical Learning: Enumerating a Collection
Practical Learning: Combining Various Disjunctions
7 o F Ne Mg Al Si
CheckedListBox button from the Common Controls section of the Toolbox. To programmatically create a checked list box, declare a variable of type
A Web Configuration File
Introduction
foreach:
Based on this description, a connection string in the Web.config file can start as follows:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
. . . No Change
name
connection-string-details"
providerName="System.Data.SqlClient" />
</connectionStrings>
. . . No Change
</configuration>
add
name " providerName="System.Data.SqlClient" /> <add name="connection-string2-name" connectionString="connection-string2-details" providerName="System.Data.SqlClient" /> . . . <add name="connection-string_n-name" connectionString="connection-string_n-details" providerName="System.Data.SqlClient" /> . . . No Change </configuration>
add add nodes. Each add.
A Web Configuration Manager
Data Source Data Source as LocalDb.
The Path to the Database
AttachDBFileNamehe SqlConnectionStringBuilder AttachDBFilename:
public string AttachDBFilename { get; set; }
|DataDirectory| to AttachDBFilenameits .mdf extension.
@{
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection("Server=YellowCastle; ");
}
Practical Learning: Creating a Connetion String
Additional Attributes
Network Library (also called Net), Application Name, Workstation ID, Encrypt, Connection Timeout, Data Source, Packet Size, AttachDBFilename, Current Language, Persist Security Info.
would "scan" the string to validate each key=value section. If it finds an unknown Key, an unknown value, or an invalid combination of key=value, it would throw an ArgumentException exception and the connection cannot be established.
Introduction to the SQL Connection
Data Entry and Functions
GETDATE() function. Here are examples:
INSERT INTO RepairOrders(CustomerName, CustomerPhone, RepairDate) VALUES(N'Annette Berceau', N'301-988-4615', ); GO INSERT INTO RepairOrders(CustomerPhone, CustomerName, RepairDate) VALUES(N'(240) 601-3795', N'Paulino Santiago', GETDATE()); GO INSERT INTO RepairOrders(CustomerName, RepairDate, CustomerPhone) VALUES(N'Alicia Katts', GETDATE(), N'(301) 527-3095'); GO INSERT INTO RepairOrders(RepairDate, CustomerPhone, CustomerName) VALUES(GETDATE(), N'703-927-4002', N'Bertrand Nguyen'); GO
SQL Selection
Introduction to SQL Operators and Operands
key1=value1;key2=value2;key_n=value_n";
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection();
connection.ConnectionString = strConnection;
}
DataSetss the necessary SQL code as the command text of the object:
should observe:
. In our databases:
[Global Survey], or [Date of Birth]. Even if you had created an object with a name that doesn't include space, when using that name, you can still include it in square brackets. Examples are [UnitedStations], [FullName], [DriversLicenseNumber], and [Country].
Opening and Closing a Connection
Closing or Deleting a Connection
SqlConnection.Close() method, which means you do not need to remember to close it.
Database Maintenance
Connecting to a Database
SQL Code
Renaming a Database
provides sp_renamedb
EXEC sp_renamedb 'ExistingName', 'NewName'
The EXEC sp_renamedb expression is required. The ExistingName factor is the name of the database that you want to rename. The NewName factor is the name you want the database to have after renaming it.Here is an example of renaming a database:
EXEC sp_renamedb 'RentalCars', 'BethesdaCarRental GO
To rename a table in a C# code, pass the EXEC sp_renamedb code as string to a SqlCommand object and call the SqlCommand.ExecuteNonQuery() method.
SELECT Something
The
SELECT what-column(s)
SELECT 226.75;
Based on this definition, instead of just being a value, the thing on the right side of SELECT must be able to produce a value. SELECT can be used with more than one value. The values must be separated by commas. Here is an example:
SELECT 'Hourly Salary', 24.85
Nesting a SELECT Statement
Because we mentioned that the thing on the right side must produce a result, you can as well use another SELECT statement that itself evaluates to a result. To distinguish the SELECT sections, the second one should be included in parentheses. Here is an example:
SELECT (SELECT 448.25);
GO
When one SELECT statement is created after another, the second is referred to as nested.
SELECT (SELECT (SELECT 1350.75));
GO
default, the caption is "(No column name)". If you want to use your own caption, on the right side of an expression, type the AS keyword followed by the desired caption. The item on the right side of the AS keyword must be considered as one word. Here is an example:You can also include the item on the right side of AS in single-quotes. Here is an example:
SELECT 24.85 AS 'HourlySalary';
AS and a closing square bracket "]". Here is an example:
SELECT 'James Knight' As FullName, 20.48 AS Salary;
Practical Learning: Opening a Query Window
string-details
If you need to use many databases in your project, you can add a separate connection string for each. This means that you can create as many add nodes as you need in your Web.config document. This would be done as follows:
details namedetails-string_n-name details
add child nodes. As a result (sorry for the repetition), the connectionStrings node is a collection of add nodes. Each add node is also referred to as a section.
To support the file name of a local database, the connection string has a factor named AttachDBFileName. To support the database file name, the SqlConnectionStringBuilder class is equipped with a property named AttachDBFilename:
.mdf extension.
Practical Learning: Creating a Connetion String
Creating a Database
Introduction
After creating the connection string, when the application executes, the compiler would "scan" the string to validate each key=value section. If it finds an unknown Key, an unknown value, or an invalid combination of key=value, it would throw an ArgumentException exception and the connection cannot be established.
Practical Learning: Creating a Database
Encrypt, Connection Timeout, Data Source, Packet Size, AttachDBFilename, Current Language, Persist Security Info.using. To specify this, in the Solution Explorer of Microsoft SQL Server, right-click the name of the database and click Open.
Practical Learning: Opening a Query Window
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2004-2019, FunctionX | Next |
|