Docsity

C# Variables and Data Types: Understanding Value and Reference Types, Study Guides, Projects, Research of Computer Science

Toggle sidebar
bg1
IT1907
02 Handout 1 *Proper ty of S TI
student.feedback@sti.edu Page 1 of 5
Data Types
Identifi ers and Keywords
An identifier is a name of a program component programmers use to unique ly identify namespaces, classes, methods, variabl es,
constants, etc. Identifiers are user-defined words. For example , in the program shown in Code Listing 1, the identifiers are
ConsoleApp, ComputeRectangleArea, length, width, area, WriteLine, and ReadKey.
Code Listing 1. Sample class with identifiers
using S ystem;
namespa ce Consol eAp p
{
class C ompute Rec tangle Area
{
static void M ain ()
{
int length , widt h, are a;
length = 50;
width = 8;
area = length * width;
Console .Write Lin e("The area of the re ctangle i s " + area);
Console .ReadK ey( );
}
}
}
The followi ng are the syntax rules when naming an identifier in C#:
•It must start with a letter of the English alphabet or an underscore characte r.
•The identifier's name can only have any combination of l etters, digits, and underscores. White spaces are not allowed.
•Identifiers are case sensitive. For example, the identifier Area is not the same with identifiers area or AREA.
•It cannot be a reserved keyword.
•The classes and methods in C# must always begin with a capital le tter.
The followi ng are the example s of valid and invalid identifiers:
Valid Identifiers
Invalid Identifiers
_score
score_
1score
1score is invalid because it begins with number.
first_Name
ScoreClass
first Name
first Name is invalid because it contains white space.
grade1
ComputeScore
class
class is an invalid identifier because it is a reserved keyword.
Table 1. Example valid identifiers
Table 2. Example invalid identifiers
Keywords are reserve d words a programming l anguage uses for its own use, and they have a special predefine d meaning to
the compiler. These cannot be used as identifiers. If you do use a keyword in a program, the compiler wil l throw an error
message. Table 3 shows the li st of keywords in C#.
abstrac t
base
bool
break
case
catch
checked
class
const
decimal
default
do
double
else
event
explici t
false
finally
fixed
for
foreach
if
implici t
in
interfa ce
interna l
lock
long
namespa ce
null
object
out
overrid e
params
protect ed
public
ref
return
sbyte
short
sizeof
static
string
struct
this
throw
try
typeof
uint
uncheck ed
unsafe
using
virtual
void
while
Table 3. C# keyword s ( Har wani , 2015)
pf3
pf4
pf5

Partial preview of the text

Download C# Variables and Data Types: Understanding Value and Reference Types and more Study Guides, Projects, Research Computer Science in PDF only on Docsity!

02 Handout 1 _Property of STI_*

Data Types

Identifiers and Keywords

An identifier is a name of a program component programmers use to uniquely identify namespaces, classes, methods,variables,

constants, etc. Identifiers are user-defined words. For example, in the program shown in Code Listing 1 , the identifiers are

ConsoleApp, ComputeRectangleArea, length, width, area, WriteLine, and ReadKey.

Code Listing 1. Sample class with identifiers using System; namespace ConsoleApp { class ComputeRectangleArea { static void Main() { int length, width, area; length = 50; width = 8; area = length * width; Console.WriteLine("The area of the rectangle is " + area); Console.ReadKey(); } } }

The following are the syntax rules when naming an identifier in C#:

• It must start with a letter of the English alphabet or an underscore character.

• The identifier's name can only have any combination of letters, digits, and underscores. White spaces are not allowed.

• Identifiers are case sensitive. For example, the identifier Area is not the same with identifiers area or AREA.

• It cannot be a reserved keyword.

• The classes and methods in C# must always begin with a capital letter.

The following are the examples of valid and invalid identifiers:

Valid Identifiers Invalid Identifiers

score score 1score 1score is invalid because it begins with number.

first_Name ScoreClass first Name first Name is invalid because it contains white space.

grade1 ComputeScore class class is an invalid identifier because it is a reserved keyword.

Table 1. Example valid identifiers Table 2. Example invalid identifiers

Keywords are reserved words a programming language uses for its own use, and they have a special predefined meaning to

the compiler. These cannot be used as identifiers. If you do use a keyword in a program, the compiler will throw an error

message. Table 3 shows the list of keywords in C#.

abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void volatile while Table 3. C# keywords (Harwani, 2015)

02 Handout 1 _Property of STI_*

Variables

A variable is an identifier and a memory location that stores a specific value. Variables hold a value that can be changed during

program execution. For example, a variable named score is assigned an initial value of 25. When the program starts, the

value of variable score will change to 25. The basic syntax of declaring a variable is as follows:

data_type identifier;

The data_type is one (1) of C#’s data types, and the identifier is the name of the variable. For example, int score;

Variables are initialized, or assigned a value, with an equal sign followed by the value. The following are some validexamplesof

declaring and initializing variables:

  • You can initialize a variable at the time of declaration. For example: int score = 25;
  • You can declare and initialize more than one (1) variable of the same time data type using a comma in a single statement: int score, age; score = 85; age = 24; int length = 8, width = 5;

When creating a program, you must define a variable with a meaningful name that is easy to understand what value must store

on it. For example, the variables gameScore and age must store integer type values. Use camelCase notation that starts with

a lowercase letter for naming local variables. For example, numberOfStudents, age, totalPrice, etc.

Constants

A constant is an identifier and a memory location whose value cannot be changed during program execution. Constants must

initialize a value at the time of declaration. The basic syntax of initializing a constant in C# is as follows:

const data_type IDENTIFIER = value;

Constants in C# are defined using the const keyword. For example: const double PI = 3.14159;. In the example, the

constant PI with the value of 3.14159 cannot be changed during program execution. The name of the constants must be in

all capital to make it easy to identify that its value must not change.

Data Types

Data types are used to specify a set of values and their operations associated with variables or constants. The values have a

particular data type because they are stored in memory in the same format and have the same operations defined for them. A

variable or constant stores data of a specific type.

When declaring a variable or constant to store a data, the appropriate data type for that data must be identified. The data type

will instruct the compiler what kind of value a variable or constant can hold and its operations. There are two (2) types of

primitive data types in C#:

  • Value types. These data types store the value directly. The data type int is a value type that stores its value in a memory

location directly.

  • Reference types. These data types do not store the actual value in a variable or constant. Instead, they store the reference

(or address) where the value is stored. The class objects , strings, and arrays are reference types because theyholdreferences

to blocks of memory and are managed on the heap.

Value Types

A data type is a value type if it holds the data within its own memory allocation. Value types directly store the values withinthe

variable. For example, consider the following figure:

Figure 1. Memory allocation for value type

In Figure 1 , the variable length of int type is assigned

a value of 50. When this statement is executed, the

compiler will instruct the computer system to directly

store 50 in the memory space allocated for the variable

length.

02 Handout 1 _Property of STI_*

From To Example int (^) long, float, or double int a = 25; double b = a; //the value of b is 25. uint (^) long, ulong, float, or double uint a = 25; long b = a; long float or double long a = 25; double b = a; ulong (^) float or double ulong a = 25; double b = a; float double float a = 25.0F; double b = a; char (^) ushort, int, uint, long, ulong, float, or double char a = 'a'; int b = a; //the value of b is 97 because the decimal value of character 'a' in ASCII table is 97 Table 5. Implicit numeric conversions (Deitel, P. and Deitel, H., 2015)

Note: There is no implicit conversion of any data type to char type, so the values of the other integral types do not

automatically convert to the char type. The bool and double data types have no possible implicit conversions to the other

data types.

  • Explicit conversion. Converting a higher precision data type to a lower precision data type is invalid, and the compiler will

return an error. For example, the statements double num1 = 25.0; int num2 = a; will return an error because the

precision of variable num1 of double data type is higher than the variable num2 of int type. However, explicit conversions

allow the users to convert a value of higher precision data type into a value of lower precision data type by using a cast

operator. The following is the general syntax of performing explicit conversion in C#:

(data_type) data_to_convert;

The (data_type) is the cast operator that will create a converted copy of the value in data_to_convert. For example, the

following statements uses a cast operator to explicitly convert data types:

//first example

int num = 25; byte b = (byte) num; //second example double price = 75.5; int varA = (int) price; //the value of variable a will be 75

In the first example, the value 25 is assigned to the variable num of int type, then the converted copy of value from variable

num is assigned to the variable b. The value stored in variable num is still an integer type because the cast operator created

a converted copy of its value as byte data type.

Explicit conversion involves the risk of losing information, i.e., from double to int data type. In the second example,

the value of the variable price of double data type is copied and converted into int data type then stored in the variable

varA of int data type. The cast operator dropped the decimal part of the floating-point number 75.5 to convert it to 75 as

int data type.

The following statements shows some of the ways on how to use the cast operator:

int a = (int) 7.9; //the return value of a is 7 double b = (double) (5 + 3); //the value of b is 8. Console.WriteLine((int) 2.5); //the output is 2 int c = 64; char d = (char) c; //the return value of d is the character '@'

The following table shows the list of all valid explicit conversions in C#.

From To

sbyte byte, ushort, uint, ulong, or char

byte sbyte or char

short sbyte, byte, ushort, uint, ulong, or char

ushort sbyte, byte, short, or char

int sbyte, byte, short, ushort, uint, ulong, or char

uint sbyte, byte, short, ushort, int, uint, long, ulong, or char

long sbyte, byte, short, ushort, int, uint, ulong, or char

02 Handout 1 _Property of STI_*

From To

ulong sbyte, byte, short, ushort, int, uint, long, or char

char sybte, byte, or short

float sbyte, byte, short, ushort, int, uint, long, ulong, or char

double sbyte, byte, short, ushort, int, uint, long, ulong, char, or double

Table 6. Explicit conversions (Deitel, P. and Deitel, H., 2015)

The explicit conversion of a data type to char data type will return the corresponding character of the value from the ASCII

table.

int a = 64; char b = (char) a; //the value of b is the character '@' because it is the corresponding character of decimal value 64 in ASCII table

REFERENCES:

Deitel, P. and Deitel, H. (2015). Visual c# 2012 how to program, 5th edition. USA: Pearson Education, Inc.

Gaddis, T. (2016). Starting out with visual c#, 4th edition. USA: Pearson Education, Inc.

Harwani, B. (2015). Learning object-oriented programming in c# 5.0. USA: Cengage Learning PTR