Introduction to Variables
Introduction to Variables
Declaring a Variable
Introduction
We know that the basic formula to declare a variable consists of indicating the desired data type and a name for the variable. Here are examples:
using System;
using System.Windows.Forms;
namespace WaterDistrinutor
{
public partial class BillPreparation : Form
{
public BillPreparation()
{
InitializeComponent();
}
private void btnCalculateTotalCharges_Click(object sender, EventArgs e)
{
double amountDue;
double environmentCharges;
double distributionCharges;
distributionCharges = double.Parse(txtDistributionCharges.Text);
environmentCharges = double.Parse(txtEnvironmentCharges.Text);
amountDue = distributionCharges + environmentCharges;
txtTotalCharges.Text = amountDue.ToString();
}
}
}
Practical Learning: Introducing Operators and Operands
Control | (Name) | Text |
Label | Meter Reading Start . . . . . . . . . . . . | |
TextBox | txtMeterReadingStarStart | 0 |
Label | Gallons | |
Label | Meter Reading End . . . . . . . . . . . . | |
TextBox | txtMeterReadingStarEnd | 0 |
Label | Gallons | |
Button | btnCalculateWaterAndSewerUsage | Calculate Water and Sewer Usage |
Label | _______________________________ | |
Label | Water and Sewer Usage . . . . . . . . . . . . | |
TextBox | txtWaterSewerUsage | |
Label | Gallons | |
Label | Water Use Charges => 4.18 per 1,000 Gallons . . . . . . . . . . . . . . . . . . . . . . | |
TextBox | txtSewerUseCharges | |
Label | Sewer Use Charges => 5.85 per 1,000 Gallons . . . . . . . . . . . . . . . . . . . . . | |
TextBox | txtSewerUseCharges | |
Label | Distribution Charges . . . . . . . . . . . . . . | |
TextBox | txtDistributionCharges | 0.00 |
Label | Environment Charges . . . . . . . . . . . . . . | |
TextBox | txtEnvironmentCharges | 0.00 |
Button | btnCalculateTotalCharges | Calculate Total Charges |
Label | _______________________________ | |
Label | Total Charges . . . . . . . . . . . . | |
TextBox | txtTotalCharges |
private void btnCalculateWaterAndSewerUsage_Click(object sender, EventArgs e) { double usage; double sewerServices; double waterUseCharges; double sewerUseCharges; double meterReadingEnd; double waterConsumption; double meterReadingStart; meterReadingStart = double.Parse(txtMeterReadingStart.Text); meterReadingEnd = double.Parse(txtMeterReadingEnd.Text); usage = meterReadingEnd - meterReadingStart; waterUseCharges = usage * 4.18; sewerUseCharges = usage * 5.85; waterConsumption = waterUseCharges / 1000; sewerServices = sewerUseCharges / 1000; txtWaterSewerUsage.Text = usage.ToString(); txtWaterUseCharges.Text = waterConsumption.ToString("F"); txtSewerUseCharges.Text = sewerServices.ToString("F"); } private void btnCalculateTotalCharges_Click(object sender, EventArgs e) { double amountDue; double waterUseCharges; double sewerUseCharges; double distributionCharges; double environmentCharges; waterUseCharges = double.Parse(txtWaterUseCharges.Text); sewerUseCharges = double.Parse(txtSewerUseCharges.Text); distributionCharges = double.Parse(txtDistributionCharges.Text); environmentCharges = double.Parse(txtEnvironmentCharges.Text); amountDue = waterUseCharges + sewerUseCharges + distributionCharges + environmentCharges; txtTotalCharges.Text = amountDue.ToString("F"); }
Declare a Variable When you Need it
As done above, you can first declare a variable, do some other things, when specify the value of the variable as long as you do this before using the variable. If your code is long, that approach can make your code difficult to read. The suggestion is to declare a variable only at the time you need it, namely at the time you are assigning a value to the variable for the first time. Here are examples:
cprivate void btnCalculateTotalCharges_Click(object sender, EventArgs e)
{
double distributionCharges = double.Parse(txtDistributionCharges.Text);
double environmentCharges = double.Parse(txtEnvironmentCharges.Text);
double amountDue = distributionCharges + environmentCharges;
txtTotalCharges.Text = amountDue.ToString();
}
Avoid Unnecessary Variable Declarations
As we saw in our introductions, the ideaa to declara a variable is to store a value in the computer memory. You do this because you anticipate that you will need to use that variable more than once. If you use a value only once, you may not need to declare a variable for it. You can use the value directly where it is needed. Here is an example:
private void btnCalculateTotalCharges_Click(object sender, EventArgs e)
{
double distributionCharges = double.Parse(txtDistributionCharges.Text);
double environmentCharges = double.Parse(txtEnvironmentCharges.Text);
txtTotalCharges.Text = (distributionCharges + environmentCharges).ToString();
}
This approach can reduce the number of lines of your code variables, from this:
private void btnCalculateWaterAndSewerUsage_Click(object sender, EventArgs e) { double waterUseCharges; double sewerUseCharges; double usage = double.Parse(txtWaterAndSewerUsage.Text); waterUseCharges = usage * 4.18; sewerUseCharges = usage * 5.85; txtWaterAndSewerUsage.Text = usage.ToString(); txtWaterUseCharges.Text = waterUseCharges.ToString("F"); txtSewerUseCharges.Text = sewerUseCharges.ToString("F"); }
To this:
private void btnCalculateWaterAndSewerUsage_Click(object sender, EventArgs e) { double waterUseCharges = double.Parse(txtWaterAndSewerUsage.Text) * 4.18; double sewerUseCharges = double.Parse(txtWaterAndSewerUsage.Text) * 5.85; txtWaterAndSewerUsage.Text = double.Parse(txtWaterAndSewerUsage.Text).ToString(); txtWaterUseCharges.Text = waterUseCharges.ToString("F"); txtSewerUseCharges.Text = sewerUseCharges.ToString("F"); }
But if you do too much, it can make your code difficult, such as going from this code:
private void btnCalculateWaterAndSewerUsage_Click(object sender, EventArgs e) { double usage; double sewerServices; double waterUseCharges; double sewerUseCharges; double meterReadingEnd; double meterReadingStart; double waterConsumption; meterReadingStart = double.Parse(txtMeterReadingStart.Text); meterReadingEnd = double.Parse(txtMeterReadingEnd.Text); usage = meterReadingEnd - meterReadingStart; waterUseCharges = usage * 4.18; sewerUseCharges = usage * 5.85; waterConsumption = waterUseCharges / 1000; sewerServices = sewerUseCharges / 1000; txtWaterSewerUsage.Text = usage.ToString(); txtWaterUseCharges.Text = waterConsumption.ToString("F"); txtSewerUseCharges.Text = sewerServices.ToString("F"); } private void btnCalculateTotalCharges_Click(object sender, EventArgs e) { double waterUseCharges; double sewerUseCharges; double distributionCharges; double environmentCharges; double amountDue; waterUseCharges = double.Parse(txtWaterUseCharges.Text); sewerUseCharges = double.Parse(txtSewerUseCharges.Text); distributionCharges = double.Parse(txtDistributionCharges.Text); environmentCharges = double.Parse(txtEnvironmentCharges.Text); amountDue = waterUseCharges + sewerUseCharges + distributionCharges + environmentCharges; txtTotalCharges.Text = amountDue.ToString("F"); }
Or this:
private void btnCalculateWaterAndSewerUsage_Click(object sender, EventArgs e) { double meterReadingStart = double.Parse(txtMeterReadingStart.Text); double meterReadingEnd = double.Parse(txtMeterReadingEnd.Text); double usage = meterReadingEnd - meterReadingStart; double waterUseCharges = usage * 4.18; double sewerUseCharges = usage * 5.85; double waterConsumption = waterUseCharges / 1000; double sewerServices = sewerUseCharges / 1000; txtWaterSewerUsage.Text = usage.ToString(); txtWaterUseCharges.Text = waterConsumption.ToString("F"); txtSewerUseCharges.Text = sewerServices.ToString("F"); } private void btnCalculateTotalCharges_Click(object sender, EventArgs e) { double waterUseCharges = double.Parse(txtWaterUseCharges.Text); double sewerUseCharges = double.Parse(txtSewerUseCharges.Text); double distributionCharges = double.Parse(txtDistributionCharges.Text); double environmentCharges = double.Parse(txtEnvironmentCharges.Text); double amountDue = waterUseCharges + sewerUseCharges + distributionCharges + environmentCharges; txtTotalCharges.Text = amountDue.ToString("F"); }
Or this:
private void btnCalculateWaterAndSewerUsage_Click(object sender, EventArgs e) { double waterUseCharges = (double.Parse(txtMeterReadingEnd.Text) - double.Parse(txtMeterReadingStart.Text)) * 4.18; double sewerUseCharges = (double.Parse(txtMeterReadingEnd.Text) - double.Parse(txtMeterReadingStart.Text)) * 5.85; double waterConsumption = waterUseCharges / 1000; double sewerServices = sewerUseCharges / 1000; txtWaterSewerUsage.Text = (double.Parse(txtMeterReadingEnd.Text) - double.Parse(txtMeterReadingStart.Text)).ToString(); txtWaterUseCharges.Text = waterConsumption.ToString("F"); txtSewerUseCharges.Text = sewerServices.ToString("F"); } private void btnCalculateTotalCharges_Click(object sender, EventArgs e) { double amountDue = double.Parse(txtWaterUseCharges.Text) + double.Parse(txtSewerUseCharges.Text) + double.Parse(txtDistributionCharges.Text) + double.Parse(txtEnvironmentCharges.Text); txtTotalCharges.Text = amountDue.ToString("F"); }
To this one:
private void btnCalculateWaterAndSewerUsage_Click(object sender, EventArgs e) { txtWaterSewerUsage.Text = (double.Parse(txtMeterReadingEnd.Text) - double.Parse(txtMeterReadingStart.Text)).ToString(); txtWaterUseCharges.Text = (((double.Parse(txtMeterReadingEnd.Text) - double.Parse(txtMeterReadingStart.Text)) * 4.18) / 1000).ToString("F"); txtSewerUseCharges.Text = (((double.Parse(txtMeterReadingEnd.Text) - double.Parse(txtMeterReadingStart.Text)) * 5.85) / 1000).ToString("F"); } private void btnCalculateTotalCharges_Click(object sender, EventArgs e) { txtTotalCharges.Text = (double.Parse(txtWaterUseCharges.Text) + double.Parse(txtSewerUseCharges.Text) + double.Parse(txtDistributionCharges.Text) + double.Parse(txtEnvironmentCharges.Text)).ToString("F"); }
If fact it can get worse (especially if you include of the things we haven't studied such as conditional statements, collections, etc).
Inferring the Value of a Variable
To make it easy for you to declare variables, the C# language provides a keywork named var. You can use it to declare a variable of any type. If you use this keyword, you must immmediately initialize the variable. This means that, unlike the actual data types we have used so far, you must initialize a var variable when you declare it. This allows the compiler to figure out the type of value of the variable. The formula to follow is:
var variable-name = value;
Here is an example:
class Employment
{
static void Main()
{
var fullName = "Martial Engolo";
double hourlySalary;
System.Console.WriteLine("Employee Details");
System.Console.WriteLine("=======================");
hourlySalary = 22.27;
System.Console.Write("Employee Name: ");
System.Console.WriteLine(fullName);
System.Console.Write("Houly Rate: ");
System.Console.WriteLine(hourlySalary);
}
}
An Anonymous Type
We saw that, to use a class, you could first declare a variable for it and initialize it. Fortunately, you don't have to use a class to initialize an object. You can declare a variable that resembles an instance of a class and initialize it as you see fit. This is referred to as an anonymous type. To use it, declare the variable using the var keyword and use the new operator to allocate memory for it. Instead of using the name of a class, type an opening and a closing curly brackets after the new operator. In the curly brackets, state a name for each member as if it were the member of the class and initialize each member variable with the desired value. After the closing curly bracket, end the declaration with a semi-colon. Here is an example:
class Exercise
{
static void Main()
{
var BookInformation = new
{
Title = "Calculus 6e Edition",
Pages = 1074,
Cover = "Hard Back"
};
}
}
After initializing the anonymous type, you can access each one of its members using the name of the variable followed by the period operator, and followed by the member variable. Here is an example:
class Exercise { static void Main() { var BookInformation = new { Title = "Calculus 6e Edition", Pages = 1074, Cover = "Hard Back" }; System.Console.WriteLine("=//= BookInformation =//="); System.Console.Write("Title: "); System.Console.WriteLine(BookInformation.Title); System.Console.Write("Nbr of Pages: "); System.Console.WriteLine(BookInformation.Pages); System.Console.Write("Type of Cover: "); System.Console.WriteLine(BookInformation.Cover); } }
This would produce:
=//= BookInformation =//= Title: Calculus 6e Edition Nbr of Pages: 1074 Type of Cover: Hard Back Press any key to continue . . .
Remember that spreading the declaration on many lines only makes it easy to read. Otherwise, you can as well include everything on the same line.
class Exercise
{
static void Main()
{
var book = new { Title = "Calculus 6e Edition", Pages = 1074 };
System.Console.WriteLine("=//= BookInformation =//=");
System.Console.Write("Title: ");
System.Console.WriteLine(BookInformation.title);
System.Console.Write("Nbr of Pages: ");
System.Console.WriteLine(BookInformation.pages);
}
}
Constants
Introduction
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.52;
inch = Meter * 39.37;
System.Console.Write(meter);
System.Console.Write(" = ");
System.Console.Write(inch);
System.Console.WriteLine("in\n");
}
}
Here is an example of running the program:
12.52 = 492.9124in
A constant is a value that never changes such as 244, "ASEC Mimosa", or 39.37. 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 let you create a constant, C# provides the const keyword. Type it to the left of the data type of a variable. When declaring a constant, you must initialize it with an appropriate value. Here is an example:
const double ConversionFactor = 39.37;
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.37; double meter, inch; meter = 12.52; inch = Meter * ConversionFactor; System.Console.Write(meter); System.Console.Write(" = "); System.Console.Write(inch); System.Console.WriteLine("in\n"); meter = 12.52; inch = Meter * ConversionFactor; System.Console.Write(meter); System.Console.Write(" = "); System.Console.Write(inch); System.Console.WriteLine("in\n"); meter = 12.52; inch = Meter * ConversionFactor; System.Console.Write(meter); System.Console.Write(" = "); System.Console.Write(inch); System.Console.WriteLine("in\n"); } }
This would produce:
12.52 = 492.9124in 12.52 = 492.9124in 12.52 = 492.9124in
To initialize a constant variable, the value on the right side of "=" 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. Before using a constant, you must first know that it exists. Second, you must know how to access it.
null: The null keyword is a constant used to indicate that a variable doesn't hold a known value.
Managing Variables
Introduction
Microsoft Visual Studio provides many tools you can use to manage code and manage your variables. 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 a 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:
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. Microsoft Visual Studio makes it easy to find and change a name wherever it is used. Consider the following code:
class Order { static void Main() { int nbr = 148; System.Console.WriteLine(nbr); } }
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.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2021, FunctionX | Next |
|