What is C#?

C# (pronounced "see sharp" or "C Sharp") is one of many .NET programming languages. It is object-oriented and allows you to build reusable components for a wide variety of application types. Microsoft introduced C# on June 26th, 2000 and it became a v1.0 product on Feb 13th 2002.

C# is an evolution of the C and C++ family of languages. However, it borrows features from other programming languages, such as Delphi and Java. If you look at the most basic syntax of both C# and Java, the code looks very similar, but then again, the code looks a lot like C++ too, which is intentional. Developers often ask questions about why C# supports certain features or works in a certain way. The answer is often rooted in it's C++ heritage.
14:30C# Tutorial

How Do I Get Started?

The C# Tutorial was created to help beginning developers and other professionals who need a quick on-ramp to the language. Plz Click Start Menu then
Visual Studio 2008. Open A Dialog Box Select New Project.
14:30C# Tutorial

The C# Keywords

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 volatile
14:24C# Tutorial

Csharp Data Types

An important part in the life of a C# programmer is the management of data types. Just as in C and C++, every variable has a fixed data type. Every data type provides a rich set of operators that can be used to perform a very special operation. Objects can be seen as data types as well, but we'll take a closer look at that later in this book.

C# Type Mono Signed Memory Range

Sbyte System.Sbyte Yes 1 byte –128 to 127

Short System.Int16 Yes 2 bytes –32768 to 32767

Int System.Int32 Yes 4 bytes –2147483648 to 2147483647

Long System.Int64 Yes 8 bytes –9223372036854775808 to 9223372036854775807

Byte System.Byte No 1 byte 0 to 255

Ushort System.Uint16 No 2 bytes 0 to 65535

Uint System.Uint32 No 4 bytes 0 to 4294967295

Ulong System.Uint64 No 8 bytes 0 to 18446744073709551615

Float System.Single Yes 4 bytes –1.5x10-45 to 3.4 x x1038

Double System.Double Yes 8 bytes –5.0x10-324 to 1.7x10308

Decimal System.Decimal Yes 12 bytes 1.0x10-28 to 7.9x1028

Char System.Char 2 bytes Unicode characters
Boolean System.Boolean 1 byte True or false
After this brief overview, we'll show you how variables and data types can be used efficiently. The following example shows how a variable can be declared and displayed on screen:
using System;

class Hello
public static void Main()
int x = 3;
Console.WriteLine("The value is " + x );
Declaring a variable works just like in C and C++. The way data is displayed is reminiscent of Java. We use the plus operator to connect two strings with each other. The output is not surprising:
[hs@localhost csharp]$ mono hello4.exe
The value is 3

Using the plus operator is truly easy, but it could also be a danger. In most cases, the plus operator is used as a mathematical operator. If it's used differently, the result might be a bit unexpected:
using System;

class Hello
public static void Main()
uint x = 3;
Console.WriteLine("The value is " + x + 1 );
Console.WriteLine("The value is " + (x + 1) );
We perform two operations that look pretty similar. However, the results differ significantly:
[hs@localhost csharp]$ mono hello5.exe
The value is 31
The value is 4
The first operation connects two strings. The second example performs an addition. As you can see, the plus operator has more than just one meaning.
14:21C# Tutorial

Csharp Explicit Conversion

using System;
class Program
static void Main(string[] args)
double x = 2.1;
int y = 12;
int z = (int)x + y; //Explicit conversion from double to int
14:20C# Tutorial

Csharp Implicit Conversion

using System;

class Program
static void Main(string[] args)
int x = 2;
double y = 12.2;
double z;
z = x + y; //x is automatically converted into a double
This is an example of csharp implicit conversion. The compiler implicitly converts x to a double. Data loss is not an issue with this operation.
14:20C# Tutorial

What is Conversion?

Conversion is the process of changing a value from one type to another.
• Implicit: Automatic compiler conversion where data loss is not an issue.
• Explicit: A conversin where data loss may happen and is recommended that the programmer writes additional processing

A common rule of thumb is that it is much easier to convert up then it is to convert down. For example, conversion from int to long is an easy operation, but converting the other way around is not so easy. Remember the long data type is a bigger type then the int data type is. To prevent data loss just remember to convert from small to large.

There may be situations where you cannot get around from converting a large data type to small. This where explicit conversion comes into play.
14:19C# Tutorial

C# Operators

Results are computed by building expressions. These expressions are built by combining variables and operators together into statements. The following table describes the allowable operators, their precedence, and associativity.
Operator category Operators
Arithmetic + - * / %
Logical (boolean and bitwise) & | ^ ! ~ && || true false
String concatenation +
Increment, decrement ++ --
Shift << >>
Relational == != <> <= >=
Assignment = += -= *= /= %= &= |= ^= <<= >>=
Member access .
Indexing []
Cast ()
Conditional ?:
Delegate concatenation and removal + -
Object creation new
Type information as is sizeof typeof
Overflow exception control checked unchecked
Indirection and Address * -> [] &
The above table includes some operator shortcuts that can be used in assignment expressions.
Here's a quick table that demonstrates operator shortcuts.
The Shortcut Operator in the expression Normal equivalent expression
x++ or ++x x = x + 1
x-- or --X x = x - 1
x += y x = x + y
x -= y x = x - y
x *= y x = x * y
x /= y x = x / y
x %= y x = x % y
x <<= y x = x << y
x >>= y x = x >> y
x &= y x = x & y
x |= y x = x | y
x ^= y x = x ^ y
14:18C# Tutorial

C# Control Statements

In this lesson, we'll be covering the major control statements which are for, while, do while,switch and if. With these under your belt, you are well on the way to becoming a seasoned programmer.

The If and else-If Statement

Programs need to make decisions. Should this statement be executed or that one? Are these parameters correct and so on. This is done using the if statement. The syntax is pretty easy.

if ( conditional expression )

This can be extended with else.

if ( conditional expression )

This can be extended with else-if.

if ( conditional expression )
else if ( conditional expression )

So if the expression is true, statement1 is executed, otherwise statement2 is executed.

The For Loop

This is the syntax of a for statement.
for ( initial statement; conditional expression; loop statement ) main statement;
Note This is the one place where there is no need to put brackets around a conditional expression.

This code sums the array and prints the total of an array with 10 values in it.
int value =0;
for (index=0 ;index < 10;index++ )
value += numbers[ index ];
printf("Value = %i",value) ;

Break and Continue

These two words apply to all the loop types, i.e. while, for and do. Each behave differently.
Break forces a loop to exit immediately. Here's an example:
int markerpos=-1;
for (index=0 ;index < 10;index++ )
if (values[index] ==-999 )
markerpos = index;
; break;
if (markerpos== 999)
printf("-1 Not located in array";
printf("-1 Found at index %i\n\r",markerpos) ;
That's a more complicated example. It searches the 10 element array values looking for a 999 value. The variable markerpos holds the position if a 999 is found. It is initialized to -1 and after the search this value is examined to see if a 999 was found.
This does the opposite of break; Instead of terminating the loop, it immediately loops again, skipping the rest of the code. So lets sum that integer array again, but this time we'll leave out elements with an index of 4 and 5.
int value =0;
for (index=0 ;index < 10;index++ )
if (index==4 || index==5)
value += numbers[index];
printf("Value = %i",value) ;
You probably won't use continue very often but it's useful on the odd occasion.

While and Do While

First is the while statement which has this syntax.
while (expression) statement
As long as the expression is true, the statement is executed.
int total =0;
int index =0;
while (total < 100)
printf("Sum of 1 to %i is %i",index,total) ;

Looping doesn't get much simpler than while. The most important thing to know with while loops is that the control expression is evaluated before the statement is run. If the expression is false, the statement is not run. So a while loop may never execute a statement.
Also because c allows a statement to be an expression it is possible to write complicated code like this
int c=10;
int a =0;
while (c--)
printf("Value of a is %i",a++) ;
c-- subtracts one from c.
Do While
Less popular than the while statement is the do while statement. This puts the expression at the end.
The syntax looks like this.
while (expression) ;
A while loop might never execute a statement if the expression is false but a do while will always execute the statement at least once.
Here is an example of a do while loop.
int count =0;
int index =9;
if (value[ index] ==999)
while ( index >= 0) ;
Break and Continue work equally well with for, while and do while loops.

About Switch Statements

When there are many choices, a switch statement may be better than an if. The syntax of a switch statement is:
switch ( expression) {

case a: statement1; break;
case b: statement2;
case d: statement3; break;
default: statement4;

Notes: Expression should be an int or a char type. e.g.
switch (character) {

case 'B':
case 'b': statement1; break;
case 'c': statement2;
case 'd': statement3; break;
default: statement4;
If the character is 'B' or 'b' then statement1 is executed, but if the character is 'c' then statement2 and statement3 are both executed. With 'd' though, only statement3 is executed. For all other characters statement4 is executed.
When a case matches, all statements from that case on, including those that follow are executed until a break is found. This is known as 'Fall Through'.
switch (value) {
case 3:statement3;
case 2:statement2;
case 1:statement1;
default: break;
14:13C# Tutorial

C# DateTime Format

This example shows how to format DateTime using String.Format method. All formatting can be done also using DateTime.ToString method.

Custom DateTime Formatting

There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).
Following examples demonstrate how are the format specifiers rewritten to the output.
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year
String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24
String.Format("{0:m mm}", dt); // "5 05" minute
String.Format("{0:s ss}", dt); // "7 07" second
String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction
String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes
String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M.
String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone

You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator.
// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)

Here are some examples of custom date and time formatting:
// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt); // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt); // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt); // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt); // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

Standard DateTime Formatting

In DateTimeFormatInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.
Following table shows patterns defined in DateTimeFormatInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.
Specifier DateTimeFormatInfo property Pattern value (for en-US culture)
t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of D and t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of d and t) M/d/yyyy h:mm tt
G (combination of d and T) M/d/yyyy h:mm:ss tt
m, M MonthDayPattern MMMM dd
y, Y YearMonthPattern MMMM, yyyy
r, R RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s SortableDateTimePattern
yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u UniversalSortableDateTimePattern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
(*) = culture independent
Following examples show usage of standard format specifiers in String.Format method and the resulting output.
String.Format("{0:t}", dt); // "4:05 PM" ShortTime
String.Format("{0:d}", dt); // "3/9/2008" ShortDate
String.Format("{0:T}", dt); // "4:05:07 PM" LongTime
String.Format("{0:D}", dt); // "Sunday, March 09, 2008" LongDate
String.Format("{0:f}", dt); // "Sunday, March 09, 2008 4:05 PM" LongDate+ShortTime
String.Format("{0:F}", dt); // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt); // "3/9/2008 4:05 PM" ShortDate+ShortTime
String.Format("{0:G}", dt); // "3/9/2008 4:05:07 PM" ShortDate+LongTime
String.Format("{0:m}", dt); // "March 09" MonthDay
String.Format("{0:y}", dt); // "March, 2008" YearMonth
String.Format("{0:r}", dt); // "Sun, 09 Mar 2008 16:05:07 GMT" RFC1123
String.Format("{0:s}", dt); // "2008-03-09T16:05:07" SortableDateTime
String.Format("{0:u}", dt); // "2008-03-09 16:05:07Z" UniversalSortableDateTime

Date Time Program

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Security.Cryptography;

public class MainClass
public static void Main()
DateTime dt1 = new DateTime(2004, 10, 19);
Console.WriteLine("dt1: {0}", dt1);
DateTime dt2 = new DateTime(2004, 10, 19, 22, 47, 35);
Console.WriteLine("dt2: {0}", dt2);
DateTime dt3 = new DateTime(2004, 10, 19, 22, 47, 35, 259);
Console.WriteLine("dt3: {0}", dt3);
14:07C# Tutorial

C# Programming Example


1. The obligatory example for any language,
3. using System;
4. public class HelloWorld
5. {
6. public static void Main(string[] args) {
7. Console.Write("Hello World!");
8. }
9. }
14:05C# Tutorial