C# is a modern,
general-purpose, object-oriented programming language developed by Microsoft
and approved by European Computer Manufacturers Association (ECMA) and
International Standards Organization (ISO).
C# was developed by
Anders Hejlsberg and his team during the development of .Net Framework.
C# is designed for
Common Language Infrastructure (CLI), which consists of the executable code and
runtime environment that allows use of various high-level languages on
different computer platforms and architectures.
Programming Features of C#
Although C# constructs
closely follow traditional high-level languages, C and C++ and being an
object-oriented programming language.
Important features of C#:
- Boolean Conditions
- Automatic Garbage Collection
- Standard Library
- Assembly Versioning
- Properties and Events
- Delegates and Events Management
- Easy-to-use Generics
- Indexers
- Conditional Compilation
- Simple Multithreading
- LINQ and Lambda Expressions
- Integration with Windows
The .Net Framework
The .Net framework is
a revolutionary platform that helps you to write the following types of
applications:
- Windows applications
- Web applications
- Web services
The .Net framework
consists of an enormous library of codes used by the client languages such as
C#. Following are some of the components of the .Net framework:
- Common Language Runtime (CLR)
- The .Net Framework Class Library
- Common Language Specification
- Common Type System
- Metadata and Assemblies
- Windows Forms
- ASP.Net and ASP.Net AJAX
- ADO.Net
- Windows Workflow Foundation (WF)
- Windows Presentation Foundation
- Windows Communication Foundation (WCF)
- LINQ
Integrated
Development Environment (IDE) for C#
Microsoft provides the
following development tools for C# programming:
- Visual Studio 2010 (VS)
- Visual C# 2010 Express (VCE)
- Visual Web Developer
C# - Program Structure
Before we study basic
building blocks of the C# programming language, let us look at a bare minimum
C# program structure
Creating Hello World Program
A C# program consists
of the following parts:
- Namespace declaration
- A class
- Class methods
- Class attributes
- A Main method
- Statements and Expressions
- Comments
Let us look at a
simple code that prints the words "Hello World"
Output
Let us look at the various parts of the given program:
- The first line of the program using System; - the using keyword is used to include the System namespace in the program. A program generally has multiple using statements.
- The next line has the namespace declaration. A namespace is a collection of classes. The HelloWorldApplication namespace contains the class HelloWorld.
- The next line has a class declaration, the class HelloWorld contains the data and method definitions that your program uses. Classes generally contain multiple methods. Methods define the behavior of the class. However, the HelloWorld class has only one method Main.
- The next line defines the Main method, which is the entry point for all C# programs. The Main method states what the class does when executed.
- The Main method specifies its behavior with the statement Console.WriteLine("Hello World");
- WriteLine is a method of the Console class defined in the System namespace. This statement causes the message "Hello, World!" to be displayed on the screen.
- The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press and it prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET.
Compiling and Executing the Program
If you are using
Visual Studio.Net for compiling and executing C# programs, take the following
steps:
- Start Visual Studio.
- On the menu bar, choose File -> New -> Project.
- Choose Visual C# from templates, and then choose Windows.
- Choose Console Application.
- Specify a name for your project and click OK button.
- This creates a new project in Solution Explorer.
- Write code in the Code Editor.
- Click the Run button or press F5 key to execute the project.
- A Command Prompt window appears that contains the line Hello World.
You can compile a C#
program by using the command-line instead of the Visual Studio IDE:
- Open a text editor and add the above-mentioned code.
- Save the file as helloworld.cs
- Open the command prompt tool and go to the directory where you saved the file.
- Type csc helloworld.cs and press enter to compile your code.
- If there are no errors in your code, the command prompt takes you to the next line and generates helloworld.exe executable file.
- Type helloworld to execute your program.
- You can see the output Hello World printed on the screen.
C# - Basic Syntax
- The using Keyword
The
first statement in any C# program is
using
System;
The using keyword
is used for including the namespaces in the program.
A program can include multiple using statements.
A program can include multiple using statements.
- The class Keyword
The class keyword
is used for declaring a class.
- Member Variables
Variables
are attributes or data members of a class, used for storing data.
In the preceding program, the Rectangle class has two member variables named
length and width.
In the preceding program, the Rectangle class has two member variables named
length and width.
- Member Functions
Functions
are set of statements that perform a specific task.
The member functions of a class are declared within the class.
Our sample class Rectangle contains three member functions:
AcceptDetails,
GetArea and
Display.
The member functions of a class are declared within the class.
Our sample class Rectangle contains three member functions:
AcceptDetails,
GetArea and
Display.
- Identifiers
An
identifier is a name used to identify a class, variable, function, or any other
user-defined item.
The basic rules for naming classes in C# are as follows:
user-defined item.
The basic rules for naming classes in C# are as follows:
- A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.
- It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.
- It should not be a C# keyword.
- Instantiating a Class
In
the preceding program, the class ExecuteRectangle contains the Main()
method and instantiates the Rectangle class.
method and instantiates the Rectangle class.
C# - Keywords
Keywords are reserved
words predefined to the C# compiler. These keywords cannot be used as
identifiers. However, if you want to use these keywords as identifiers, you may
prefix the keyword with the @ character.
In C#, some
identifiers have special meaning in context of code, such as get and set are
called contextual keywords.
The following table
lists the reserved keywords and contextual keywords in C#:
Reserved 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
|
in (generic
modifier)
|
int
|
interface
|
internal
|
is
|
lock
|
long
|
namespace
|
new
|
null
|
object
|
operator
|
out
|
out (generic
modifier)
|
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
|
|||||
Contextual Keywords
|
||||||
add
|
alias
|
ascending
|
descending
|
dynamic
|
from
|
get
|
global
|
group
|
into
|
join
|
let
|
orderby
|
partial (type)
|
partial
(method)
|
remove
|
select
|
set
|
C# - Data Types
Such as if you want to work with string value then you will have to assign string type variable to work with.
C# provides two types of data types:
1.Value types
2.Reference types.
A Value type data type stores copy of the value whereas the Reference type data types stores the address of the value.
Value Types
Data Types
|
Size
|
Values
|
sbyte
|
8 bit
|
-128 to 127
|
byte
|
8 bit
|
0 to 255
|
short
|
16 bit
|
-32,768 to 32,767
|
ushort
|
16 bit
|
0 to 65,535
|
int
|
32 bit
|
-2,147,483,648 to 2,147,483,647
|
uint
|
32 bit
|
0 to 4,294,967,295
|
long
|
64 bit
|
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
|
ulong
|
64 bit
|
0 to 18,446,744,073,709,551,615
|
char
|
16 bit
|
0 to 65535
|
float
|
32 bit
|
-1.5 x 1045 to 3.4 x 1038
|
double
|
64 bit
|
-5 x 10324 to 1.7 x 10308
|
decimal
|
128 bit
|
-1028 to 7.9 x 1028
|
Reference Types
C# - Varables
int [ ] array =new int[4];
string [ ] array =new string [10];
Data Types
|
Size
|
Values
|
string
|
Variable
length
|
0-2
billion Unicode characters
|
object
|
---
|
---
|
C# - Varables
A variable is nothing
but a name given to a storage area that our programs can manipulate.
Type
|
Example
|
Integral types
|
sbyte, byte, short,
ushort, int, uint, long, ulong, and char
|
Floating point types
|
float and double
|
Decimal types
|
decimal
|
Boolean types
|
true or false
values, as assigned
|
Nullable types
|
Nullable data types
|
Some valid variable
definitions are shown here:
int i, j, k;
char c, ch;
float f, salary;
double d;
You can initialize a
variable at the time of definition as:
int i = 100;
The following example
uses various types of variables:
When the above code is
compiled and executed, it produces the following result:
C# -Conditional Statements
This statement allows you to branch your code
depending on whether or not a certain condition is met.
In C# are the following 2 conditional branching
statements:
- IF statement
- Switch statement
IF Statement
The if statement allows you to test whether or not a
specific condition is met.
Syntax
If(<Condition>)
<statements>;
Else
if(<Condition>)
<statements>;
---------------------
-----------------------
Else
<statements>;
Example
W.A.P to find the
greatest number using an if statement:
Switch Statement
The switch statement
compares two logical expressions.
Syntax
Switch(<Expression>)
{
Case <Value>
:
<stmts>
Break;
-----------------------
-------------------------
------------------------
Default :
<stmts>
Break;
It is specially
designed for accessing the values of an array and collection.
Syntax
- Foreach(type var in coll/Arr)
- {
- < statement >;
- }
There may be a
situation, when you need to execute a block of code several number of times. In
general, the statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on.
Programming languages
provide various control structures that allow for more complicated execution
paths.
C# provides following
types of loop to handle looping requirements. Click the following links to
check their detail.
Loop Type
|
Description
|
It repeats a
statement or a group of statements while a given condition is true. It tests
the condition before executing the loop body.
|
|
It executes a
sequence of statements multiple times and abbreviates the code that manages
the loop variable.
|
|
It is similar to a
while statement, except that it tests the condition at the end of the loop
body
|
|
You can use one or
more loop inside any another while, for or doWhile loop.
|
An array stores a
fixed-size sequential collection of elements of the same type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Declaring Arrays
To declare an array in
C#, you can use the following syntax:
datatype[ ] arrayName;
For example,
int [ ] array =new int[4];
string [ ] array =new string [10];
double[ ] balance;
C# - Exception Handling
An
exception is a problem that arises during the execution of a program. A C#
exception is a response to an exceptional circumstance that arises while a
program is running, such as an attempt to divide by zero.
Exceptions
provide a way to transfer control from one part of a program to another. C#
exception handling is built upon four keywords: try, catch, finally, and throw.
- Try: A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.
- Catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
- Finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
- Throw: A program throws an exception when a problem shows up. This is done using a throw keyword.