Last Modified 5-1-2010




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


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

Decisions are made in C# with the if/else/elseif constructs. The coding rules for C# constructs are as follows:

C# Coding Rules

  • Use spaces to separate the words in each statement.
  • Use exact capitalization for all keywords, class names, object names, variable names, etc.
  • End each statement with a semicolon;
  • Each block of code must be enclosed in braces: {}. That includes the block of code that defines the body of the method.

With that background it is time to develop the code for the above requirements. Change the code in the Calculate Button event procedure as follows:

Calculate Code 2

Figure CS-32: C# Invoice Total Calculate Button Event Handler ver 2.0

We are now going to test our code by following the steps below:

  • Press the Start Debugging Start Debugging Symbol symbol.

  • Enter the value 600 in the Subtotal TextBox:

  • Press the <ENTER> key on your keyboard or the Calculate Button button.

  • Repeat Subtotal values of 400, 200 and 50 to validate each of the test cases and percentages.

Below is the illustration for sample output with Subtotal input=600:

Invoice Total Runtime 2

Figure CS-33: C# Invoice Total Form At Runtime with Subtotal=600

C# Coding Recommendations:

  • Use indentation and extra spaces to align statements and blocks of code so they reflect the structure of the program.
  • Use spaces to separate the words, operators, and values in each statement.
  • Use blank lines before and after groups of related statements.

Code Editor and Error List Windows with syntax errors displayed.

  • Visual Studio checks the syntax of your C# code as you enter it. if a syntax error occurs it is highlighted with a wavy underline in the code editor, and you can place the mouse pointer over it to display a description of the error.
  • If the Error List window is open, all of the build errors are listed in that window. Then, you can double-click on any error in the list to take you to its location in the Code Editor. When you correct the error, it is removed from the error list.
  • If the Error List window is closed, you can display it by selecting the Error List command from the View menu. Then, if you want to hide this window, you can click on its Auto-Hide button.
  • Visul Studio doesn't detect some errors until the project is built. As a result, you may encounter more syntax errors when you build and run the project.

C# Comments Description and Syntax

  • Comments: are used to help document what a progam does and what the code within it does.
  • Single-line Comment: Type // before the comment.
    • Use to add a comment as its own line or
    • Use to add a comment at the end of a line.
  • Delimited Comment: Type /* at the start of the comment and */ at the end.
    • Additional asterisks can be added to help identify lines in the comment.

The Visual Studio C# Help Window

  • You can display a Help window be selecting an object in the Form Designer or positioning the insertion point in a keyword in the Code Editor and pressing F1.
  • You can also display a Help Window by selecting a command (such as Index, Contents or Search) from Visual Studio's Help menu.
  • The Help window works like a web browser and can display help topics that are available from your computer or from the Internet. You can use the buttons in its toolbar to navigate between help topics to your list of favorite topics.
  • The Help Window is divided into two panes. The left pane displays the Index, Content, and Help Favorites tabs that let you locate the help topics you want to display. The right pane displays each help topic in a separate window.
  • If you click on the Search button, the right pane will display a Search tab that lets you search for help topics by entering a word or phrase.
  • If you click on the How Do I button, the right pane will display a How Do I tab that lets you go to a topic by clicking on a link.
  • To close a tab, click on the Close button when the tab is active. To display a tab, click on the tab or select it from the Active Files drop-down list that's next to the Close button.

C# Language Essentials

At this point, we begin to delve into some details for coding C# statements. These will include coding arithmetic operations, selction and iteration statements, methods, data validation, arrays, collections dates and strings.

C# Built-In Data Types

C# Keyword Bytes .NET Type Description
byte 1 Byte A positive integer value form 0 to 255
sbyte 1 SBtye A signed integer value form -128 to 127
short 2 Int16 An integer from -32,768 to +32,767
ushort 2 UInt16 An unsigned integer fromm 0 to 65,535
int 4 Int32 An integer from -2,147,438,648 to +2,147,483,647
uint 4 UInt32 An unsigned integer from 0 to 4,294,967,295
long 8 Int64 An integer from 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong 8 UInt64 An unsigned integer from 0 to +18,446,744,073,709,551,615
float 4 Single 3.402823E38 to 1.401298E45 for negative values;
1.401298E45 to 3.402823E38 for positive values
double 8 Double 1.79769313486232E308 to 4.94065645841247E-324 for negative values;
4.94065645841247E324 to 1.79769313486232E308 for positive values
decimal 16 Decimal 0 through +/-79,228,162,514,264,337,593,543,950,335 with no decimal point;
0 through +/-7.9228162514264337593543950335 with 28 places to the right of the decimal;
smallest nonzero number is +/-0.0000000000000000000000000001 (+/-1E-28).
char 2 Char A single Unicode character
bool 1 Boolean A true or false value
string variable String 1 to approx 2 billion Unicode characters

Figure CS-34: C# Built-In Data Types


  • The built-in data types are actually aliases for the data types defined by the Common Type System of the .NET Framework
  • All of the data types shown in this figure are value types, which means that they store their own data. In contrast, reference types store a reference to the area of memory where the data is stored.
  • A bit is a binary digit that can have a value of one or zero. A byte is a group of 8 bits. As a result, the number of bits for each data type is the number of bytes multiplied by 8.
  • Integers are whole numbers, and the first 8 data types above provide for signed and unsigned integers of various sizes.
  • Since the decimal type is the most accurate non-integer data type, it is typically used to store monetary values.
  • The Unicode character set provides for over 65,000 characters, with two bytes used for each character. Each character maps to an integer value.
  • The older ASCII character set that's used by most operating systems provides for 256 characters with one byte used for each character. In the Unicode character set, the first 256 characters correspond to the 256 ASCII characters.
  • A bool data type stores a Boolean value that is either true or false.

How to Declare Variables in C#


type VariableName = value;


int Counter = 1;
long NumberOfBytes=20000;
double InterestRate=8.125;
double StartCount=3.65e9;
char Letter='A';
string Line1="This is a string";


  • Variable: Stores a value that can change as the program executes.
    • You must declare the variable type before you use it.
    • You must assign an initial value to the variable before you can use it.

  • Common intitial values are 0 for integers, 0.0 for floats and doubles, and true or false for Boolean
  • To declare or initialize more than one variable for a single data type in a single statement, use commas to separate the variable names or assignments.
  • The letter f as a suffix identifies the value as a float.
  • The letter m as a suffix identifies the value as a decimal.
  • The keywords for datatypes in C# must be with all lowercase letters.

How to Declare a Constant in C#


const type ConstantName = value;


const int DaysInNovember=30;
const decimal SalesTax=.075m;

How to Code Arithmetic Expressions

Operator Name Description
+ Addition Adds two operands
- Subtraction Subtracts the right operand from the left operand.
* Multiplication Multiplies the right operand and the left operand.
/ Division Divides the right operand into the left operand.
If both operands are integers, then the result is an integer.
% Modulus Returns the value that is left over after dividing the right operand into the left operand.
+ Positive Sign Returns the value of the operand.
- unary negative Changes a positive value to a negative and vice versa.
++ Increment Adds 1 to the operand (x=x+1)
-- Decrement Subtracts 1 from the operand (x=x-1)

Figure CS-35: C# Arithmetic Operators


  • An arithmetic expression consists of one or more operands and arithmetic operators.
  • The first five operations are called binary operators because they operate on two operands.
  • The last four operators are called unary operators because they operate on just one operand.

How to code assignment statements

Operator Name Description
= Assignment Assigns a new value to the variable.
+= Addition Adds the right operand to the value stored in the variable and assigns the result to the variable
-= Subtraction Subtracts the right operand from the value stored in the variable and assigns the result
to the variable.
*= Multiplication Multiplies the variable by the right operand and assigns the result to the variable.
/= Division Divides the variable by the right operand and assigns the result to the variable.
If the variable and the operand are both integers, then the result is an integer.
%= Modulus Divides the variable by the right operand and assigns the remainder to the variable.

Figure CS-36: C# Arithmetic Assignment Operators


  • Assignment Statement: Consists of a variable, an equals sign, and an expression.
  • When the assignment statement is executed, the expression is evaluated and the result is stored in the variable
  • Besides the equals sign, C# provides the five other assignment operators shown above.
  • These operators provide a shorthand way to code common assignment operators.




66 Total=Subtotal-DiscountAmount;