Introduction to Variables and Data Types
Introduction to Variables and Data Types
Fundamentals of Variables
Introduction
A variable is a value used in the code of a webpage. Before using a variable, you must let the compiler know. This is referred to as declaring a variable. You can declare a variable in the body of the code delimiters, @{ and }. To declare a variable, you must provide two pieces of information. The first indicates the type of value of the variable. This is called a data type. In C# (and many other languages, but not all languages), a data type is represented by a word referred to as a reserved word or a keyword (in some languages such as C and C++, a data type can be specified using a combination of keywords).
Practical Learning: Introducing Values
<!DOCTYPE html> <html> <head> <title>Fun Department Store</title> </head> <body> <h2>Fun Department Store - Inventory</h2> @{ } </body> </html>
A variable must have a name. This is the second piece of information you must provide. There are strict rules you must follow to specify the name of a variable. In our lessons, here are the rules we will follow to name things:
Besides these rules, you can also create your own rules but that follow the above restrictions. For example:
When naming your things such as variables, you must avoid reserved words, also called keywords. These keywords are:
abstract | as | async | await | base | bool | |
continue | break | byte | case | catch | char | checked |
class | const | is | override | stackalloc | ulong | |
fixed | delegate | for | lock | params | static | unchecked |
internal | finally | interface | float | out (generic) | ||
out (methods) | do | foreach | long | private | string | unsafe |
sizeof | double | goto | namespace | protected | struct | ushort |
uint | else | if | new (generic) | public | switch | using |
decimal | enum | implicit | new (LINQ) | readonly | this | virtual |
default | event | in (foreach) | new (variable) | ref | throw | void |
explicit | in (generic) | null | return | true | volatile | |
extern | int | object | sbyte | try | while | |
false | operator | sealed | short | typeof |
There are other names that are not considered C# keywords but should be avoided because they may cause a conflict in your code. They are referred to as contextual keywords. They are:
add | descending | global | let | remove | var |
alias | dynamic | group | orderby | select | where (generic) |
ascending | from | into | partial (method) | set | where (query) |
async | get | join | partial (type) | value | yield |
await |
There are situation when you want to, you need to, or in fact you must, use a keyword. To do that, preceede the name of the variable with the @symbol.
C# is case-sensitive. This means that the names Case, case, and CASE are different.
Based on our introduction to data types and variables names, the basic formular to declare a variable is:
data-type variable-name;
If you must use a keyword as the name of a variable, the formula to use is:
data-type @variable-name;
Initializing a Variable
Initializing a variable consists of giving it an initial value when the variable is declared. The formula you use is the same for all types but the value you want to use depends on the data type. To initialize a variable, start with its data type, followed by a name for the variable, followed by =, followed by the desired but appropriate value, and end with a semicolon. The formula to follow is:
data-type variable-name = desired-value
The Value of a Web Control
To get the value of a webcontrol of a webpage, use the following formula:
@{ Request["control-name"] }
You can assign that expression to a variable.
Values on a Webpage
The values of a webpage display on a browser. To display the value held by a variable, somewhere in the code of a webpage, type @ followed by the name of the variable.
Fundamentals of Strings
A string is an empty space, a character, a word, or a group of words. Primarily, the value of a string starts with a double-quote and ends with a double-quote. An example of a string is "Welcome to the wonderful world of web development!".
To declare a variable for a string, use the string keyword. You can initialize it with an empty space, a character, a symbol, a word, or a group of words. The value of the variable must be included in double-quotes.
Practical Learning: Introducing Strings
<!DOCTYPE html> <html> <head> <title>Fun Department Store</title> </head> <body> <h2>Fun Department Store - Inventory</h2> @{ string itemName = "Petite Jersey Matte Dress"; string itemSize = "Small"; } <p>Item Name: @itemName</p> <p>Sizee: @itemSize</p> </body> </html>
<!DOCTYPE html> <html> <head> <title>Fun Department Store</title> </head> <body> <h2>Fun Department Store - Inventory</h2> @{ string itemName = "Petite Jersey Matte Dress"; string itemSize = "Small"; } <table> <tr> <td><b>Item Name:</b></td> <td>@itemName</td> </tr> <tr> <td><b>Size:</b></td> <td>@itemSize</td> </tr> </table> </body> </html>
<!DOCTYPE html> <html> <head> <title>Fun Department Store</title> </head> <body> <h2>Fun Department Store - Inventory</h2> @{ string itemName = "Petite Jersey Matte Dress"; string itemSize = "Small"; } <form name="fromDepartmentStore" method="post"> <table> <tr> <td><b>Item Name:</b></td> <td><input type="text" name="txtItemName" value="@itemName" /></td> </tr> <tr> <td><b>Size:</b></td> <td><input type="text" name="txtItemSize" value=@itemSize /></td> </tr> </table> </form> </body> </html>
Converting a Value to a String
Many of the values with which you will deal are not string. Sometimes, to use one of those values where a string would be used, you should (sometimes must) convert that value to a string. To do this, after the value or the name of the variable, type .ToString().
Introduction to Natural Numbers
An integer is a natural number that is made of one or a combination of digits that are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 in the sequence of your choice.
To declare a variable for an integer, use a keyword named int. To initialize the variable or to assign a value to it, provide a number that uses only digits.
If the value of a webcontrol is an integer, you must first convert that value from a string. To do this, after Request["control-name"], type .AsInt(). You can then assign that expression to an integer variable.
Converting an Integral Value to a String
As mentioned already, to convert a natural number to a string, after the value or the name of the variable, type .ToString().
Practical Learning: Introducing Integers
<!DOCTYPE html> <html> <head> <title>Fun Department Store</title> </head> <body> <h2>Fun Department Store - Inventory</h2> @{ int itemNumber = 284075; string itemName = "Petite Jersey Matte Dress"; string size = "Small"; } <form name="fromDepartmentStore" method="post"> <table> <tr> <td><b>Item #:</b></td> <td><input type="text" name="txtItemNumber" value="@itemNumber" /></td> </tr> <tr> <td><b>Item Name:</b></td> <td><input type="text" name="txtItemName" value="@itemName" /></td> </tr> <tr> <td><b>Size:</b></td> <td><input type="text" name="txtItemSize" value=@size /></td> </tr> </table> </form> </body> </html>
<!DOCTYPE html> <html> <head> <title>Fun Department Store</title> <style> #main-title { font-size: 22px; font-weight: bold; text-align: center; font-family: Garamond, 'Times New Roman', serif } .sub-title { font-size: 18px; text-align: center; font-family: Garamond, 'Times New Roman', serif } .container { margin: auto; width: 365px; } .grave { font-weight: bold } .left-column { width: 100px; } .tbl-content-holder { width: 100% } </style> </head> <body> <div class="container"> <p id="main-title">Fun Department Store</p> <p class="sub-title alignment grave">Inventory Creation</p> @{ int itemNumber = 284075; string itemName = "Petite Jersey Matte Dress"; string size = "Small"; } <form name="fromDepartmentStore" method="post"> <table class="tbl-content-holder"> <tr> <td class="left-column grave">Item #:</td> <td><input type="text" name="txtItemNumber" value="@itemNumber" style="width: 60px" /></td> </tr> <tr> <td class="grave">Size:</td> <td><input type="text" name="txtItemSize" value=@size /></td> </tr> <tr> <td class="grave">Item Name:</td> <td><input type="text" name="txtItemName" value="@itemName" style="width: 200px" /></td> </tr> </table> </form> </div> </body> </html>
Introduction to Decimal Numbers in C#
Overview
A floating-point number is one made of one or two sections, with one section required. The required section is one or a combination of digits, as we saw for an integer.
To declare a variable for a floating-point number, use a data type named decimal. Here is an example:
@{
int @int = 128;
decimal salary;
}
Like an integer, a floating-point number can consist of a natural number. If you are initializing the variable with a natural number, simply assign that number to the variable. Here is an example:
@{
decimal = 428;
}
Unlike an integer, a floating-point number can include a second part that represents a fraction of 1. That is, a number divided by 100, as in number / 100. That second part is referred to as the precision portion.
When specifying the value of a decimal number, if the value includes a precision portion, the value must be followed by either m or M (on its right side). Here is an example:
@{
decimal distance = 296.73M;
}
Even if the value is provided as a natural number, you can still include the letter. Here is an example:
@{
decimal = 296M;
}
If the decimal part of a number is 0 or includes only 0s, you can omit that part. If the integral part is 0, you can omit that 0. Here is an example:
@{
decimal distance = 296.73M;
decimal salary = 64800m;
decimal portion = .8804M;
}
If the value of a webcontrol is a decimal number, you must first convert that value from a string. To do this, after Request["control-name"], type .AsDecimal(). You can then assign that expression to a decimal variable.
Practical Learning: Introducing Decimal Numbers
<!DOCTYPE html> <html> <head> <title>Fun Department Store</title> <style> #main-title { font-size: 22px; font-weight: bold; text-align: center; font-family: Garamond, 'Times New Roman', serif } .sub-title { font-size: 18px; text-align: center; font-family: Garamond, 'Times New Roman', serif } .container { margin: auto; width: 365px; } .grave { font-weight: bold } .left-column { width: 100px; } .tbl-content-holder { width: 100% } </style> </head> <body> <div class="container"> <p id="main-title">Fun Department Store</p> <p class="sub-title alignment grave">Inventory Creation</p> @{ int itemNumber = 284075; string itemName = "Petite Jersey Matte Dress"; string size = "Small"; decimal unitPrice = 138.95m; } <form name="fromDepartmentStore" method="post"> <table class="tbl-content-holder"> <tr> <td class="left-column grave">Item #:</td> <td><input type="text" name="txtItemNumber" value="@itemNumber" style="width: 60px" /></td> </tr> <tr> <td class="grave">Size:</td> <td><input type="text" name="txtItemSize" value=@size /></td> </tr> <tr> <td style="font-weight: bold">Unit Price:</td> <td><input type="text" name="txtItemSize" value="@unitPrice" /></td> </tr> <tr> <td class="grave">Item Name:</td> <td><input type="text" name="txtItemName" value="@itemName" style="width: 200px" /></td> </tr> </table> </form> </div> </body> </html>
Converting a Floating-Point Value to a String
To convert a decimal value to a string, after the value or the name of the variable, type .ToString("F"). There are many other options or techniques but this will be enough for now.
Primary Topics on C# Variables
C# as an Inferred Language
As mentioned previously, initializing a variable is the process of assigning an initial value to it immediately when it is declared. When declaring a variable, if you plan to initialize it, in other words if you already know the initial and type of value you want it to hold, you can use a type named var. The formula to follow is:
var data-type variable-name = desired-value
If you decide to use this keyword, you must initialize the variable (on the same line). Here is an example:
@{
var salary = 64800m;
}
After initializing the variable, the compiler would become aware of the data type that must be applied to the variable. For this reason, C# is referred to as an inferred language.
Updating a Variable
Assigning a value to a variable consists of giving it a (new) value. This is done after the variable has been declared, whether it was initialized or not. In this case, you can first declare the variable by specifing its data type, its name and a semicolon. Then, on another line, type the name of the variable, followed by =, and the value. This can be done as follows:
@{
data-type variable-name;
variable-name = desired-value;
}
Here is an example:
@{ decimal distance; var salary = 64800; distance = 296; }
Another technique is to change the value of an initialized variable. In this case, after declaring and initializing a variable, on another line, assign a different value to the variable. This can be done as follows:
@{
data-type variable-name = initial-value;
variable-name = desired-value; Error
}
Declaring Many Variables
You can declare each variable on its own line as we have done so far. Different variables can be declared with the same data type. Here is an example:
@{
string firstName;
string lastName;
}
When various variables use the same data type, instead of declaring each on its own line, you can declare two or more of these variables on the same line. Here is an example:
@{
string firstName, lastName;
}
The variables can also be initialized. In this case, a variable must have its own initialization. You don't have to initialize each variable if it is not required. Here are examples:
@{
string firstName = "Daniel", middleInitial, lastName = "Ndo"
}
Introduction to the Nullity of a Variable
A value is referred to as null when it cannot be clearly determined.
When declaring a variable for a primitive data type, to indicate that a variable can hold a null value, add a question mark to it. Here are examples:
<!DOCTYPE html> <html> <head> <title>Exercise</title> </head> <body> <h1>Exercise</h1> @{ int? number = 0; decimal ? nbr = 0; int ?expression = 0; } <p>Number = @number</p> </body> </html>
Managing Variables in Microsoft Visual Studio
Accessing a Variable
The Code Editor of Microsoft Visual Studio provides many tools to assist you in managing your code. 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 one second) 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:
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:
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.
Introduction
A constant is a value that never changes. Examples are 244, "ASEC Mimosa", 39.37. These are constant values you can use in your program any time. You can also create your own constants. To create a constant, type the const keyword to the left of a variable. You must immediately initialize that variable with an appropriate value. Here is an example:
@{ const decimal ConversionFactor = 39.37M; }
Once a constant has been created and it has been appropriately initialized, you can use its name where the desired constant is needed. Here is an example:
@{
const decimal conversionFactor = 39.37m;
}
With this feature, 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.
Built-in Constants
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, or rather the .NET Framework, also provides various constants.
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.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|