Last Modified 5-1-2010

IUSB

Home

C#


Introduction to C#

.NET Framework

VS2008 IDE

How C# is Compiled

Start Visual Studio


Windows Form App


C# OOP Coding

C# Code Example


C# Coding Rules

Recommendations

Error Window

C# Comments

C# Help Window

Language Essentials

C# Data Types

Declare Variables

Declare Constants

Arith. Expressions

Assign Statements


Operator Precedence

Type Casting

Math Class

C# Strings

String Esc Sequences

Convert Data Types


ToString Formatting

Variable Scope Use

C# Enumeration Use

C# Nullable Types

Program #2


C# Code Control

Relational Operators

Logical Operators

If-Else Statement

Switch Statement


C# Arithmetic Operator Order of Precedence

  1. Increment and Decrement (++ --)
  2. Positive and Negative (+ -)
  3. Multiplication, Division, and Modulus (* / %)
  4. Addition and Subtraction (+ -)

Description

  • Unless parentheses are used, the operations in an expression take place from left to right in the order of precedence
  • To specify the sequence of operations, you can use parentheses. Then, the operations in the innermost sets of parentheses are done first, followed by the operations in the next sets, and so on.
  • When you use an increment or decrement operator as a prefix to a variable, the variable is incremented or decremented and then the result is assigned. But when you use an increment or decrement operator as a postfix to a variable, the result is assigned and then the variable is incremented or decremented.

Examples

int a=5;
int b=5;
int y=++a; //a=6, y=6
int z=b++; //b=6, z=5


How to work with Type Casting in C#

Description

  • If you code an assignment statement that assigns a value with a less precise data type to a variable with a more precise data type, C# automatically converts the less precise data type to the more precise data type. This can be referred to as an implicit cast.
  • When you code an arithmetic expression, C# implicitly casts operands with less precise data types to the most precise data type used in the expression.
  • To code an assignment statement that assigns a value with a more precies data type to a variable with a less precise data type, you must code the less precise data type in parentheses preceding the value to be assigned. This can be referred to as an explicit cast.
  • You can also use an explicit cast in an arithmetic expression. Then, the casting is done before the arithmetic operations.

How implicit casting works

Casting from less precise to more precise data types

byte → short → int → long → float → double → decimal

char → int

Examples

	double grade= 93;				//convert int to double

	int letter='A';					//convert char to int

	double a=95;
int b=86, c=91;
double average=(a+b+c)/3; //convert b and c to double values //(average = 90.6666

How to code an explicit cast

The syntax for coding an explicit cast

(type) expression;

Examples

	int grade = (int) 93.75;			//convert double to int (grade=93)
	char letter = (char) 65;			//convert int to char (letter = 'A')
	
	double a=95.0;
	int b=86, c=91;
	int average =((int)a+b+c)/3;			//convert a to int value (average=90)

	decimal result = (decimal) b / (decimal) c;	//result has decimal places	
			

How to use the C# Math Class

Description

  • To use one of the static methods of the Math class, code the class name, a dot, the method name, and one or more arguments in parentheses. The arguments provide the values that are used by the method.
  • The Round method rounds a decimal argument to the specified precision which is the number of significant decimal digits. If the precision is omitted, the number is rounded to the nearest whole number
  • If you round a number with a decimal value of .5 to a whole number, the number is rounded to the nearest even number. This is referred to as banker's rounding.
  • The Pow method raises the first argument to the power of the second argument. Both arguments must have the double data type.
  • The Sqrt method returns the square root of the specified argument, which can have any numeric data type.
  • The Min and Max methods return the minimum and maximum of two arguments. The two arguments must have the same data type.

Four static methods of the Math class

The syntax of the Round method:

Math.Round (decimalNumber [ ,precision])


The syntax of the Pow method:

Math.Pow (number, power)


The syntax of the Sqrt method:

Math.Sqrt (number)


The syntax of the Min and Max methods:

Math.{Min | Max} (number1, number2)


Statement Result
Math.Round (23.75); 24
Math.Round (23.5); 24
Math.Round (24.5); 24
Math.Round (23.754, 2); 23.75
Math.Round (23.755, 2); 23.76
Math.Pow (5, 2); 25
Math.Sqrt (20.25); 4.5
Math.Max (23.75, 20.25); 23.75
Math.Min (23.75, 20.25); 20.25

Figure CS-37: Results from C# static methods of the Math class



How to work with Strings in C#

Description

  • A string can consist of any characters in the character set including letters, numbers, and special characters like *, &, and #.
  • To specify the value of a string, you can enclose text in double quotes. This is known as a string literal.
  • To assign a null value to a string, you can use the null keyword. This means that the value of the string is unknown.
  • To assign an empty string to a string, you can code a set of double quotes with nothing between them. This usually indicates that the value of the string in known, but the string doesn't contain any characters.
  • To join, or concatenate, a string with another string or value data type, use a plus sign. If you concatenate a value data type to a string, C# will automatically convert the value to a string so it can be used as part of the string.
  • When you append one string to another, you add one string to the end of another. To do that, you can use assignment statements.
  • The += operator is a shortcut for appending a string expression to a string variable.
How to declare and initialize a string
string Message1 = "Invalid data entry";
string Message2 = "";
string Message3 = null;

How to Join Strings
string FirstName = "Bob";
string LastName = "Smith"
string FullName = FirstName + " " + LastName;
//FirstName is "Bob"
//LastName is "Smith"
//Full Name is "Bob Smith"

How to Join a String and a Number
double Price = 14.95;
string PriceString = "Price: " + Price;

How to Append one String to Another
string FirstName="Bob";
string LastName="Smith";
string FullName=FirstName + " ";
FullName += LastName;
//FirstName is "Bob"
//LastName is "Smith"
//FullName is "Bob "
//FullName is "Bob Smith"

How to Append one string to another with the += Operator
string FirstName="Bob";
string LastName="Smith";
string FullName=FirstName+" ";
FullName+=LastName;
//FirstName is "Bob"
//LastName is "Smith"
//FullName is "Bob "
//FullName is "Bob Smith"

Figure CS-38: C# String Declaration and Concatenation Examples



C# String Escape Sequences and Special Characters

Key Description
\n New Line
\t Tab
\r Return
\\ Backslash
\" Quotation

Figure CS-39: C# String Common Escape Sequences


Within a string, you can use escape sequences to include certain types of special characters:

Code Result
string Code="JSPS";
decimal Price = 49.5;
string Result =
 "Code: " + Code + "\n" +
 "Price: $" + Price + "\n";



Code: JSPS
Price: $49.50
string Names =
 "Joe\tSmith\rKate\tLewis\r"
Joe    Smith
Kate   Lewis
string path="C:\\C#.Net\\Files";
C:\C#.Net\Files
string Message=
  "Type \"x\" to exit";

Type "x" to exit

Figure CS-40: C# String Examples that use escape sequences


To code a verbatim string literal, you can code an @ sign, followed by an opening double quote, followed by the string, you can enter backslashes, tabs, new line characters, and other special characters without using escape sequences. However, to enter a double quote within a verbatim string literal, you must enter two double quotes:

Code Result
string Names=@"Joe    Smith
Kate   Lewis";
Joe    Smith
Kate   Lewis
string Path=@"C:\C#.Net\Files"; C:\C#.Net\Files
string Message=
  @"Type ""x"" to exit";

Type "x" to exit

Figure CS-41: C# String Examples that use Verbatim (@ symbol) String Literals



C# Methods to Convert Data Types

The Convert class contains static methods for converting all of the built-in data types:

Method Description
ToDecimal (value) Converts the value to the decimal data type.
ToDouble (value) Converts the value to the double data type.
ToInt32 (value) Converts the value to the int data type.
ToChar (value) Converts the value to the char data type.
ToBool (value) Converts the value to the Boolean data type.
ToString (value) Converts the value to the string data type.
Parse (string) A static method that converts the specified string to an equivalient data type.

Figure CS-42: C# Common static methods of the Convert Class


The ToString and Parse methods are included in all of the data structures.

Examples:

Conversion statements that use the ToString and Parse Methods
double Sales=2574.98;
string SalesString=Sales.ToString();
Sales=Double.Parse(SalesString);

//double to string
//string to double
Conversion Statements that use the Convert Class
double Subtotal=Convert.ToDouble(txtSubtotal.Text);
int Years=Convert.ToInt32(txtYears.Text);
txtSubtotal.Text=Convert.ToString(Subtotal);
int SubtotalInt=Convert.ToInt32(Subtotal);
//String to double
//string to int
//double to string
//double to int

Figure CS-43: C# Conversion Using ToString and Parse Methods