You are on page 1of 39

Rapid Application

Development
C# Programming Constructs
Objectives
• After completing this topic, you will be able to:
• Explain how to declare variables and assign values.
• Use operators to construct expressions.
• Create and use arrays.
• Use decision statements.
• Use iteration statements
Declaring Variables and Assigning Values
Objectives
• After completing this lesson, you will be able to:
• Describe the purpose of variables.
• Describe the purpose of data types.
• Explain how to declare and assign variables.
• Explain how variable scope determines where a variable is accessible in an
application.
• Explain how to convert data in a variable to a different data type.
• Describe best practices for using read-only variables and constants.
What Are Variables?
• A variable represents a named location in memory for a piece of data.
• Variables store values required by the application in temporary
memory locations.
• A variable has the following six facets:
• Name. Unique identifier that refers to the variable in code.
• Address. Memory location of the variable.
• Data type. Type and size of data that the variable can store.
• Value. Value at the address of the variable.
• Scope. Defined areas of code that can access and use the variable.
• Lifetime. Period of time that a variable is valid and available for use.
What Are Data Types?
• A variable holds data that has specified type.
• C# is a type-safe language, which means that the compiler guarantees
that values that are stored in variables are always of the appropriate
type.
Commonly Used Data Types
Declaring and Assigning Variables
• Before you can use a variable, you must declare it so that you can specify its name and
characteristics.
• C# is case-sensitive.
• If you use the name MyData as the identifier of a variable, this is not the same as
myData.
• You can declare two variables at the same time called MyData and myData and C# will
not confuse them, although this is not good practice.
• Identifiers
• The name of a variable is referred to as an identifier.
• C# has specific rules concerning the identifiers that you can use:
• An identifier can only contain letters, digits, and underscore characters.
• An identifier must start with a letter or an underscore.
• An identifier for a variable should not be one of the keywords that C# reserves for its own use.
Declaring and Assigning Variables …
• When you declare a variable, you reserve some storage space for that
variable in memory.
• You must specify the type of data that it will hold.
• You can declare multiple variables in a single declaration by using the
comma separator; all variables declared in this way have the same
type.
• The syntax for declaring variables is shown in the following code
example.
DataType variableName;
// OR
DataType variableName1, variableName2;
Assigning a Value to a Variable
• After you declare a variable, you can assign a value to it for later use in the
application by using an assignment statement.
• You can change the value in a variable as many times as you want during the
application.
• The assignment operator (=) assigns a value to a variable.
• The syntax of a variable assignment is shown in the following code example.
variableName = value;
• The value on the right side of the expression is assigned to the variable on the left
side of the expression.
• The following code example declares an integer called price and assigns the number
10 to the integer.
int price = 10;
Assigning a Value to a Variable …
• The following code example assigns the number 20 to an existing integer variable called price.
price = 20;

• You can also assign variables when you declare them.


• The following code example shows the syntax of a variable declaration and assignment.
DataType variableName = value;

• The type of the expression must match the type of the variable, otherwise your program will not
compile.
• For example, the code in the following code example will not work because you cannot assign a
string value to an integer variable.
int numberOfEmployees;
numberOfEmployees = "Hello";
• C# does not allow you to use an unassigned variable.
• You must assign a value to a variable before you can use it; otherwise, your program might not
compile.
Implicitly Typed Variables
• When you declare variables, you can also use the var keyword instead of
specifying an explicit data type such as int or string.
• When the compiler sees the var keyword, it uses the value that is assigned to
the variable to determine the type.
• Consequently, you must initialize a variable that is defined in this way when it
is defined, as shown in the following code example.
var price = 20;
• In this example, the price variable is an implicitly typed variable.
• Implicitly typed variables are useful when you do not know, or it is difficult to
establish explicitly, the type of an expression that you want to assign to a
variable.
What Is Variable Scope?
• The scope of a variable determines the parts of a program that can access that
variable.
• If you attempt to reference a variable outside its scope, the compiler will generate
an error.
• Levels of Scope
Variables can have one of the following levels of scope:
• Block
• Procedure
• Class
• Namespace
• These levels of scope progress from the narrowest (block) to the widest
(namespace).
Block Scope
• A block is a set of statements that is enclosed within initiating and terminating declaration
statements, such as a loop.
• If you declare a variable within a block, you
can use it only within that block.
• The lifetime of the variable is still that of the entire block.
• The following code example shows how to declare a local variable
called area with block-level scope.

if (length > 10)


{

int area = length * length;

}
Procedure Scope
• Variables that are declared within a procedure are not available outside that
procedure.
• Only the procedure that contains the declaration can use the variable.
When you declare variables in a block or procedure, they are known as local
variables.
• The following code example shows how to declare a local variable called
name with procedure-level scope.
void ShowName()
{
string name = "Bob";
MessageBox.Show("Hello " + name);
}
Class Scope
• If you want the lifetime of a local variable to extend beyond the lifetime of the
procedure, declare the variable at class-level scope.
• When you declare variables in a class or structure, but not inside a procedure, they are known as class variables.
• You can assign a scope to class variables by using an access modifier.
• The following code example shows how to declare a local variable called message with
class-level scope.

private string message;


void SetString()
{
message = "Hello World!";
}
void ShowString()
{
MessageBox.Show(message);
}
Namespace Scope
• When you declare variables at class level by using the public keyword, they are available to all procedures within
the namespace.
• The following code example shows you how to declare a variable called message in one class that you can access
in another class.
public class CreateMessage
{
public string message = "Hello";
}

public class DisplayMessage


{
public void ShowMessage()
{
CreateMessage newMessage = new CreateMessage();
MessageBox.Show(newMessage.message);
}
}
Converting a Value to a Different Data Type
• When you are designing applications, you may need to convert data
from one type to another.
• Conversions are necessary when a value of one type must be assigned
to a variable of a different type.
• For example, you might need to convert the string value "99" that you
have read from a text file into the integer value 99 that you can
store in an integer variable.
• The process of converting a value of one data type to another is called
conversion or casting.
Implicit and Explicit Conversions
• There are two types of conversions in the .NET Framework:
• Implicit conversion. Automatically performed by the common
language runtime (CLR) on operations that are guaranteed to succeed
without losing information.
• Explicit conversion. Requires you to write code to perform a
conversion that otherwise could lose information or produce an error.
• Explicit conversion reduces the possibility of some bugs in your code
and makes your code more efficient.
• C# prohibits implicit conversions that lose precision.
Implicit Conversions
• An implicit conversion occurs when a value is converted automatically from one
data type to another.
• The conversion does not require any special syntax in the source code.
• C# only allows safe implicit conversions, such as widening of integers.
• The following code example shows how data is converted implicitly from an integer to a long
type.
int a = 4;
long b;
b = a; // Implicit conversion of int to long
• This conversion always succeeds and never results in a loss of information.
• However, the converse conversion is not true; you cannot implicitly convert a long value to an
int type because this conversion risks losing information (the long value might be outside the
range that the int type supports).
The following table shows the implicit type
conversions that are supported in C#.
Explicit Conversions
• In C#, you can use a cast operator to perform explicit conversions. A cast
specifies the type to convert to, in round brackets.
• The syntax for performing an explicit conversion is shown in the following
code example.
DataType variableName1 = (castDataType) variableName2;
• You can only perform meaningful conversions in this way, such as converting a
long to an int type.
• You cannot use a cast if the format of the data has to physically
change, such as if you are converting a string to an integer.
• To perform these types of conversions, you can use the methods of the
System.Convert class.
Using the System.Convert Class
• The System.Convert class provides methods that can convert a base data type to another base
data type.
• These methods have names such as ToDouble, ToInt32, ToString, and so on.
• All languages that target the CLR can use this class.
• You might find this class easier to use for conversions because Microsoft IntelliSense helps you
locate the conversion method that you need.
• The following code example converts a string to an int type.
string possibleInt = "1234";
int count = Convert.ToInt32(possibleInt);
• In addition to the Convert.ToString method, many types implement their own ToString method.
• The following code example converts an int to a string type.
int number = 1234;
string numberString = count.ToString();
Read-Only Variables and Constants
• Read-only variables and constants enable you to store data just like
you can with any other variables in C#.
• However, these variables have some subtle differences.
• You can use read-only variables and constants to store data that does
not change.
• You can use read-only variables or constants for many values such as:
• The number of hours in a day.
• The speed of light.
• The number of degrees in a circle.
Comparing Read-Only Variables and
Constants
• There is a subtle difference between using a read-only variable and
using a constant.
• When you use a constant in an application, you can only initialize the
constant when it is declared.
• However, you can initialize a read-only variable in its declaration or in
the constructor of the class that contains the read-only variable.
• Therefore, you can only define and initialize constants at design time
and you cannot assign a different value to the constant when your
application runs.
Syntax
• You declare read-only variables by using the readonly keyword, as the
following code example shows.
readonly DataType variableName = Value;
• You declare constants by using the const keyword, as the following
code example shows.
const DataType variableName = Value;
Examples
• The following code example declares a constant to store the current date and time.
• This example uses the DateTime class and the Now property, which enables you
to compute the current date and time at run time.
• If you tried to use this approach with a constant, you would get a compile error.
readonly string currentDateTime = DateTime.Now.ToString();
• The following code example declares a PI constant to calculate the area and
circumference of a circle with a radius of 5.
const double PI = 3.14159;
int radius = 5;
double area = PI * radius * radius;
double circumference = 2 * PI * radius;
Using Expressions and Operators
• Objectives
• After completing this section, you will be able to:
• Describe the purpose of an expression.
• Describe the purpose of operators.
• Explain how to specify operator precedence.
• Explain the best practices for concatenating string values.
What Is an Expression?
• Expressions are the fundamental constructs that you use to evaluate and
manipulate data.
• Expressions are collections of operands and operators.
• Operands are values, for example, numbers and strings.
• They can be constant (literal) values, variables, properties, or method-call results.
• Operators define operations to perform on operands, for example, addition or
multiplications.
• Operators exist for all of the basic mathematical operations in addition to some
more advanced operations, such as logical comparison or the manipulation of the
bits of data that constitutes a value.
• All expressions are evaluated to a single value when your application runs.
Examples
a
a+1
a+b–2
"Answer: " + c.ToString()
b * System.Math.Tan(theta)
What Are Operators?
• Operators combine operands together into expressions.
• Operator Types
• Operators fall into the following three categories:
• Unary.
• This type of operator operates on a single operand.
• For example, you can use the - operator as a unary operator.
• To do this, you place it immediately before a numeric operand, and it converts the value of the operand to its
current value multiplied by –1.
• Binary.
• This type of operator operates on two values.
• This is the most common type of operator, for example, *, which multiplies the value of two operands.
• Ternary.
• There is only one ternary operator in C#.
• This is the ? : operator and it is used in conditional expressions
The following table shows the operators that you can use in C#, grouped by type.
Incrementing and Decrementing Variables
• If you want to add 1 to a variable, you can use the + operator, as the following code
example shows.
count = count + 1;
• However, adding 1 to a variable is so common that C# provides its own operator just
for this purpose: the ++ operator.
• To increment the variable count by 1, you can write the statement in the following
code example.
count++;
• Similarly, C# provides the –– operator that you can use to subtract 1 from a
variable, as the following code example shows.
count--;
• The ++ and –– operators are unary operators.
Using Compound Assignment Operators
• If you want to add 42 to the value of a variable, you can combine the assignment
operator and the addition operator.
• For example, the statement in the following code example adds 42 to a variable called answer.
• After this statement runs, the value of answer is 42 more than it was before.
answer = answer + 42;
• However, adding a value to a variable is so common that C# lets you perform this
task in a shorthand manner by using the operator +=.
• To add 42 to answer, you can write the statement in the following code example.
answer += 42;
• You can use this shortcut to combine any arithmetic operator with the assignment operator, as
the following table shows.
• These operators are collectively known as the compound assignment operators.
Using Compound Assignment Operators

Specifying Operator Precedence
• An expression can contain a complex series of operators and operands.
• The order in which the operators are processed and the operands are evaluated depends on the
operators themselves.
• The operators that you use to build an expression each have an associated precedence that determines
the order in which they are processed.
• Also, operators have a particular associativity, which determines the order in which they are
processed in relation to operators with a matching precedence.
• To make expressions work in exactly the way you want them to, you can control processing
order by using parentheses.
• Operator Precedence
• Some operators have a higher precedence than others, which means that they are
processed before other operators.
• For example, in the following code example, the division is performed before the addition.
a = b + 1 / 2;
The following table shows the precedence of operators
from highest at the top to lowest at the bottom.
Operator Associativity
• When you use operators of the same precedence, the operator associativity is used to
determine the order of processing.
• Operators are either right-associative or left-associative.
• Left-associative operators are processed from left to right, for example,
the / operator, as the following code example shows.
a/5/b
• Here, a is divided by 5 and then the result of that division is divided by b.
• All binary operators are left-associative apart from assignment operators, which are
right-associative, as the following code example shows.
a=b=c
• Here, the value of c is assigned to b, and then the value of b is assigned to a.
Using Parentheses
• You can use parentheses to control the order of processing and change the
precedence in an expression.
• Any part of an expression that you surround with parentheses is processed
before the part of the expression that is not inside the parentheses, as the
following code example shows.
a = (b + 1) / 2;
• Here, the (b + 1) part of the expression is processed first, and the result of
that operation is divided by 2 to determine the value that is assigned to a.
• You can nest parentheses to further control the order of expression
execution.

You might also like