You are on page 1of 20

C# Language Fundamentals

C# Development
Introduction to C#
.NET framework offers a myriad of languages which puts us programmers into a deep thought
process about which programming language best suits our needs.
It is One of the .Net Object oriented Programming languages. Which we can use for writing business
logic to any application.Which language is the "best" language choice? If you are a VB wizard, should
you takethe time to learn C# or continue to use VB.NET? Are C# ASP.NET pages "faster" thanVB .NET
ASP.NET pages? These are questions that you may find yourself asking,especially when you're just
starting to delve into .NET. Fortunately the answer is simple:there is no "best" language. All .NET
languages use, at their root, functionality from the set of classes provided by the .NET Framework.
Therefore, everything you can do in VB.NET you can do in C#, and vice-a-versa. The differences occur
in three main areas: syntax, object-oriented principles, and the Visual Studio .NET IDE. Syntax concerns
the statements and language elements. Object Oriented differences are less obvious, and concern
differences in implementation and feature sets between the two languages. IDE differences include things
like compiler settings or attributes. There is also a fourth area of difference: language features that are
present in one language but have no equivalent in the other.
If you are more familiar with Java, JScript, or C/C++, you may find C#'s syntax more familiar than
VB.NET's.
A good question that has to be answered in order to keep you interested in learning C# is Why
should you learn another programming language when you already doing enterprise development in C++
or Java. The very answer at the first go will be C# is intended to be the premier language for writing
NGWS (Next Generation of Windows Services) applications in the enterprise computing world. The
programming language C# derives from C and C++; however apart from being entirely object oriented it
is type safe and simple too. If you are a C/C++ programmer your learning curve should be flat. Many C#
statements including expressions and operators have been taken directly taken from your favourite
language An important point about C# is that it simplifies and modernizes C++ in the areas of classes,
namespaces and exception handling. Much of complex features have not been included or in fact hidden
in C# to make it easer to use and more importantly less error prone for e.g. no more macros, templates
and no multiple inheritances (Few of you might not like it.) C# provides you with convenient features like
garbage collection, versioning and lot more.

The only expense that I can think of is that your code operates in safe mode, where no pointers
are allowed. However if you want to use pointers you are not restricted from using it via unsafe code- and
no marshalling is involved when calling the unsafe code.

CUI Applications (Character user interface)


It is also called Console or Command line Applications
It will be executed in the Command Prompt.
Note: =>.cs is the extension for C# Apps
=>csc is sub Compiler for C#
Syntax: using Namespaces;
---------------namespace NameSpaceName
{
public class ClassName
{
Methods
-------}
}
e.g : - //demo.cs
//Sample Program in C#
using System;
namespace Xyz
{
public class Class1
{
public static void Main()
{
Console.WriteLiine("Hello,World");

}
}
}
1. Open the Notepad and type the following program.
2. Save the file as Demo.cs
3. Go to Visual Studio Command Prompt from Start->All Programs - >Visual Studio 2008 -> Visual
Studio Tools
4. On the command prompt, go to the directory, where you saved the file.
5. Type cs Demo.cs to compile the program.
6. Type Demo to run the program.
c:\csc demo.cs
c:\demo.exe

The program starts with the using statement. Then, we declare a class called Class1. All code in C# must
be written inside a class Next, we have written Main(). The word Main() indicates this is the start of the
program. This is where the C# system start the executing(running) the program. Thus, Main() is the entry
point(starting point) of any program. All statements written inside
Main() are executed line by line. The Main() block is started using a starting curly brace { and terminated
using an ending curly brace }.Whatever you want to write inside Main() must be enclosed within this pair
of curly braces. On the same lines, whatever you write inside the class, must be enclosed within { ... }.
In the above program, we have written just one command/statement Console.WriteLine().This command
is used display text on the VDU screen. Whatever you put inside Console.WriteLine() gets printed on the
screen, when you run the program. In this case, it is Hello World.
//Singleline coments
/*Multiline Comnents*/
mscorlib.dll
System
Console
WriteLine()
Note: -mscorlib.dll assembly will be referred into every application automatically.
D:\ csc -r:mscorlib.dll demo.cs

C# Features
By design, C# is the programming language that most directly reflects the underlying Common
Language Infrastructure (CLI). Most of its intrinsic types correspond to value-types implemented by the
CLI framework. However, the language specification does not state the code generation requirements of
the compiler: that is, it does not state that a C# compiler must target a Common Language Runtime, or
generate Common Intermediate Language (CIL), or generate any other specific format. Theoretically, a
C# compiler could generate machine code like traditional compilers of C++ or Fortran.
Some notable distinguishing features of C# are:

There are no global variables or functions. All methods and members must be declared within
classes. Static members of public classes can substitute for global variables and functions.

Local variables cannot shadow variables of the enclosing block, unlike C and C++. Variable
shadowing is often considered confusing by C++ texts.

C# supports a strict Boolean datatype, bool. Statements that take conditions, such as while and if,
require an expression of a type that implements the true operator, such as the boolean type. While
C++ also has a boolean type, it can be freely converted to and from integers, and expressions such
as if(a) require only that a is convertible to bool, allowing a to be an int, or a pointer. C# disallows
this "integer meaning true or false" approach on the grounds that forcing programmers to use
expressions that return exactly bool can prevent certain types of common programming mistakes
in C or C++ such as if (a = b) (use of assignment = instead of equality ==).

In C#, memory address pointers can only be used within blocks specifically marked as unsafe,
and programs with unsafe code need appropriate permissions to run. Most object access is done
through safe object references, which always either point to a "live" object or have the welldefined null value; it is impossible to obtain a reference to a "dead" object (one which has been
garbage collected), or to a random block of memory. An unsafe pointer can point to an instance of
a value-type, array, string, or a block of memory allocated on a stack. Code that is not marked as
unsafe can still store and manipulate pointers through the System.IntPtr type, but it cannot
dereference them.

Managed memory cannot be explicitly freed; instead, it is automatically garbage collected.


Garbage collection addresses the problem of memory leaks by freeing the programmer of
responsibility for releasing memory which is no longer needed.

In addition to the try...catch construct to handle exceptions, C# has a try...finally construct to


guarantee

execution

of

the

code

in

the

finally

block.

Multiple inheritance is not supported, although a class can implement any number of interfaces.
This was a design decision by the language's lead architect to avoid complication and simplify
architectural requirements throughout CLI.

C# is more type safe than C++. The only implicit conversions by default are those which are
considered safe, such as widening of integers. This is enforced at compile-time, during JIT, and,
in some cases, at runtime. There are no implicit conversions between booleans and integers, nor
between enumeration members and integers (except for literal 0, which can be implicitly
converted to any enumerated type). Any user-defined conversion must be explicitly marked as
explicit or implicit, unlike C++ copy constructors and conversion operators, which are both
implicit by default.

Enumeration members are placed in their own scope.

C# provides properties as syntactic sugar for a common pattern in which a pair of methods,
accessor (getter) and mutator (setter) encapsulate operations on a single attribute of a class.

Full type reflection and discovery is available.

C# currently (as of version 4.0) has 77 reserved words.

Checked exceptions are not present in C# (in contrast to Java). This has been a conscious decision
based on the issues of scalability and versionability.

C# Data Types
CTS separates datatypes into two categories:

Value types

Reference types

Value types are plain aggregations of data. Instances of value types do not have referential identity nor a
referential comparison semantics - equality and inequality comparisons for value types compare the actual
data values within the instances, unless the corresponding operators are overloaded. Value types are
derived from System.ValueType, always have a default value, and can always be created and copied.
Some other limitations on value types are that they cannot derive from each other (but can implement
interfaces) and cannot have an explicit default (parameterless) constructor. Examples of value types are
some primitive types, such as int (a signed 32-bit integer), float (a 32-bit IEEE floating-point number),
char (a 16-bit Unicode code unit), and System.DateTime (identifies a specific point in time with
nanosecond precision). Other examples are enum (enumerations) and struct (user defined structures).
In contrast, reference types have the notion of referential identity - each instance of a reference type is
inherently distinct from every other instance, even if the data within both instances is the same. This is
reflected in default equality and inequality comparisons for reference types, which test for referential
rather than structural equality, unless the corresponding operators are overloaded (such as the case for

System.String). In general, it is not always possible to create an instance of a reference type, nor
to copy an existing instance, or perform a value comparison on two existing instances, though
specific reference types can provide such services by exposing a public constructor or
implementing a corresponding interface (such as ICloneable or IComparable). Examples of
reference types are object (the ultimate base class for all other C# classes), System.String (a
string of Unicode characters), and System.Array (a base class for all C# arrays).
Both type categories are extensible with user-defined types.

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.
Operators with their precedence and Associativity

Category (by
precedence)

Operator(s)

Associativity

Primary

x.y f(x) a[x] x++ x-- new typeof default checked


unchecked delegate

left

Unary

+ - ! ~ ++x --x (T)x

right

Multiplicative

* / %

left

Additive

+ -

left

Shift

<< >>

left

Relational

< > <= >= is as

left

Equality

== !=

right

Logical AND

&

left

Logical XOR

left

Logical OR

left

Conditional AND

&&

left

Conditional OR

||

left

Null Coalescing

??

left

Ternary

?:

right

Assignment

= *= /= %= += -= <<= >>= &= ^= |= =>

right

Left associativity means that operations are evaluated from left to right. Right associativity mean all
operations occur from right to left, such as assignment operators where everything to the right is
evaluated before the result is placed into the variable on the left.
Most operators are either unary or binary. Unary operators form expressions on a single variable, but
binary operators form expressions with two variables.

C# Keywords
Keywords are predefined, reserved identifiers that have special meanings to the compiler. They cannot
be used as identifiers in your program unless they include @ as a prefix. For example, @if is a valid
identifier but if is not because if is a keyword.
The first table in this topic lists keywords that are reserved identifiers in any part of a C# program. The
second table in this topic lists the contextual keywords in C#. Contextual keywords have special meaning
only in a limited program context and can be used as identifiers outside that context. Generally, as new
keywords are added to the C# language, they are added as contextual keywords in order to avoid breaking
programs written in earlier versions

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
A contextual keyword is used to provide a specific meaning in the code, but it is not a reserved word in
C#. Some contextual keywords, such as partial and where, have special meanings in two or more
contexts.

add

alias

ascending

async

await

descending

dynamic

from

get

global

group

into

join

let

orderby

partial (type)

partial (method)

remove

select

set

value

var

where (generic type constraint)

where (query clause)

yield

Programming Constructs
C# provides the following conditional constructs
if .. else
Syntax:if ( < condition > )
{
statements
}
else
{
statements
}
The else part is optional and can be omitted. The working of if .. else construct is very simple and follows
the pattern - If this is true Ill do that or else Ill do something else. The statements included within the if
block are executed when the condition specified in if, is true, otherwise the statements inside the else
block are executed. In case, there is no else statement, the execution flow continues to the proceeding
statements.
Heres an example
Console.WriteLine("Enter your age:");
int Age = Convert.ToInt32(Console.ReadLine());
if (Age < 18)
{
Console.WriteLine("You are not permitted in here.");
}
else
{
Console.WriteLine("You may come in.");
}
switch .. case Construct
Switch case facilitates easy branching when the condition is pertaining to a single expression. Each

supplied Value is preceded by a case construct.


Syntax:switch (< expression >)
{
case Expression_1;
statements
break;
case Expression_2;
statements
break;
.
}
Console.WriteLine("Enter the month (mm)");
int Month = Convert.ToInt32(Console.ReadLine());
switch (Month)
{
case 1:
Console.WriteLine("January");
break;
case 2:
Console.WriteLine("February");
break;
case 3:
Console.WriteLine("March");
break;
case 4:
Console.WriteLine("April");

break;
case 5:
Console.WriteLine("May");
break;
case 6:
Console.WriteLine("June");
break;
case 7:
Console.WriteLine("July");
break;
case 8:
Console.WriteLine("August");
break;
case 9:
Console.WriteLine("September");
break;
case 10:
Console.WriteLine("October");
break;
case 11:
Console.WriteLine("November");
break;
case 12:
Console.WriteLine("December");
break;

default:
Console.WriteLine("There are only 12 Months.");
break;
}
Depending on the value entered by the user (1-12), the appropriate month will be displayed. For any other
value, the default case will be executed and the message There are only 12 Months. will be displayed.
A Set of instructions that are repeated is called a loop. Suppose you want to print numbers from 1 - 10.
You could do that using Console.WriteLine statement for each of the 10 numbers. But, what if you had to
print numbers from 1 - 1000? Using the computers iterative power is a much better approach.

Looping
C# supports 3 kinds of loops which are discussed below:The for loop
This loop is generally used for arithmetic operations, where we are aware of the starting and end point of
the loop.
Syntax of for loop is as follows:for(< initialization >;< condition >;< increment/decrement >)
{
statements
}
To print numbers within a range, say 1 - 1000, we declare a counter variable (preferably single character
variable like I), initialize it to the starting number (1) and keep incrementing its value by 1 until the
number exceeds the end point (1000). Off course, we would have the body of the loop where the
operation would be done, in this case, displaying the numbers on screen.
for(int I = 1; I <= 1000; I++)
{
Console.WriteLine(I);
}
Lets break the for statement down:Initialization: int I = 1

Condition: I <= 1000


Increment: I++
All the parts here are optional and can be left out. So, you can initialize the variable I, above the for
statement and leave out the initialization block. The code would look like this (; I <= 1000; I++).
Similarly, you could remove the condition part to make the loop infinite or you can include the increment
statement within the body of the for statement itself (inside the { and } brackets).
Another variation of a for statement is the empty loop which does not contain any body:
for(int I = 1; I <= 1000; I++);
Such a for statement is followed by the semicolon.
The while loop
The for loop cannot be used when the range of the loop is unknown (Well, actually it can, but the
approach would not be logical). Say, you want to continue inputting values from the user as long he
wishes to. This can be easily implemented by the while statement.
Syntax:while(< condition >)
{
statements
}
We dont have initialization and increment/decrement slot over here. These need to be implemented
additionally.
bool Continue = true;
while(Continue == true)
{
int A;
Console.WriteLine("Please Enter a Number");
A = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Continue (True/False)");

Continue = Convert.ToBoolean(Console.ReadLine());
}
We have declared a boolean variable Continue which we use to check whether to continue repeating the
process. It has been initialized to true, so that the loop is executed for the first time. The users choice of
whether to continue with the loop or not, is stored in Continue. As long as the user enters true, the
statements

within

the

body

of

the

while

loop

would

keep

on

executing.

Anything that can be implemented using for loop, can also be done using the while loop. Below is the
code to print numbers from 1 - 1000 using while.
int I = 1;
while(I <= 1000)
{
Console.WriteLine(I);
I++;
}
The do while loop
The do while loop is a variation of the while loop in which the condition is evaluated at the end of the
loop. Thus, the loop is executed at least once. Recall the first while program we did. The bool variable
continue stores the users choice. However, for the first iteration, it does not store the choice. In such a
scenario, we had to initialize continue with the value true so that the loop is executed for the first time. A
better approach would be to use the do while loop and check the condition at the end. The code for which
is given below
bool Continue;
do
{
int A;
Console.WriteLine("Please Enter a Number");
A = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Continue (True/False)");
Continue = Convert.ToBoolean(Console.ReadLine());
}
while(Continue == true);

Note: The while part in the do while loop needs to be terminated with the semicolon.

Arrays
Arrays are probably one of the most wanted topics in C#. The focus of this article is arrays
in C#. The article starts with basic definitions of different array types and how to use them
in our application. Later, the article covers the Arrays class and its methods, which can be
used to sort, search, get, and set an array's items.

Introduction
In C#, an array index starts at zero. That means the first item of an array starts at the 0th
position. The position of the last item on an array will total number of items - 1. So if an
array has 10 items, the last 10th item is at 9th position.
In C#, arrays can be declared as fixed length or dynamic.
A fixed length array can store a predefined number of items.
A dynamic array does not have a predefined size. The size of a dynamic array increases as
you add new items to the array. You can declare an array of fixed length or dynamic. You
can even change a dynamic array to static after it is defined.
Let's take a look at simple declarations of arrays in C#. The following code snippet defines
the simplest dynamic array of integer types that does not have a fixed size.
int[] intArray;

As you can see from the above code snippet, the declaration of an array starts with a type
of array followed by a square bracket ([]) and name of the array.
The following code snippet declares an array that can store 5 items only starting from index
0 to 4.
int[] intArray;
intArray = new int[5];

The following code snippet declares an array that can store 100 items starting from index 0
to 99.
int[] intArray;
intArray = new int[100];

Defining arrays of different types


In the previous code snippet, we saw how to define a simple array of integer type. Similarly,
we can define arrays of any type such as double, character, and string.
In C#, arrays are objects. That means that declaring an array doesn't create an array. After
declaring an array, you need to instantiate an array by using the "new" operator.
The following code snippet defines arrays of double, char, bool, and string data types.
double[] doubleArray = new double[5];
char[] charArray = new char[5];
bool[] boolArray = new bool[2];
string[] stringArray = new string[10];

Initializing Arrays
Once an array is declared, the next step is to initialize an array. The initialization process of
an array includes adding actual data to the array.
The following code snippet creates an array of 3 items and values of these items are added
when the array is initialized.
// Initialize a fixed array
int[] staticIntArray = new int[3] {1, 3, 5};

Alternative, we can also add array items one at a time as listed in the following code
snippet.
// Initialize a fixed array one item at a time
int[] staticIntArray = new int[3];
staticIntArray[0] = 1;
staticIntArray[1] = 3;
staticIntArray[2] = 5;

The following code snippet declares a dynamic array with string values.
// Initialize a dynamic array items during declaration
string[] strArray = new string[] { "Mahesh Chand", "Mike Gold", "Raj Beniwal", "Praveen Kumar",
"Dinesh Beniwal" };

Accessing Arrays
We can access an array item by passing the item index in the array. The following code
snippet creates an array of three items and displays those items on the console.
// Initialize a fixed array one item at a time
int[] staticIntArray = new int[3];
staticIntArray[0] = 1;
staticIntArray[1] = 3;

staticIntArray[2] = 5;
// Read array items one by one
Console.WriteLine(staticIntArray[0]);
Console.WriteLine(staticIntArray[1]);
Console.WriteLine(staticIntArray[2]);

This method is useful when you know what item you want to access from an array. If you
try to pass an item index greater than the items in array, you will get an error.

Accessing an array using a foreach Loop


The foreach control statement (loop) is used to iterate through the items of an array. For
example, the following code uses foreach loop to read all items of an array of strings.
// Initialize a dynamic array items during declaration
string[] strArray = new string[] { "Mahesh Chand", "Mike Gold", "Raj Beniwal", "Praveen Kumar",
"Dinesh Beniwal" };
// Read array items using foreach loop
foreach (string str in strArray)
{
Console.WriteLine(str);
}

This approach is used when you do not know the exact index of an item in an array and
needs to loop through all the items.

Methods
odName(params DataType [] ArrayName)
{
}
Enumerations
Enumerations are types that inherit from System.Enum. The elements of an
enumeration are expressed in words rather than numbers, which make it convenient for
understanding the meaning of the value being used. Enumerations symbolically represent a
set of values of one of the primitive integral types.
The type of the elements of an enumeration can be byte, short, int or long. If no
type is
specified explicitly, the default type is int.
Example:
enum month : byte
{Jan = 2, Feb = 5, Mar = 10};

Explanation:
In the above code segment, an enumeration type month is declared. The underlying type of
the elements has been specified as byte. It has three elements viz: Jan, Feb and Mar.
These three elements have been assigned specific values. In case of an enumeration, if no
values are specified, the value of the first element corresponds to 0 and so on

eg: public enum Colors


{
Red,
Blue,
Green
}
How to Access the Enum Statements
syntax: EnumName.Statement
eg: Colors.Red
Structures
A structure allows you to create your own custom data types and it contains one or
more members that can be of different data types. It can contain fields, methods, etc.
Structures are very similar to classes but there are some restrictions present in the case of
structures that are absent in the case of classes. For example you cannot initialize structure
members. Also you cannot inherit a structure whereas classes can be inherited. Another
important feature of structures differentiating it from classes is that a structure can't have a
default parameter-less constructor or a destructor. A structure is created on the stack and
dies when you reach the closing brace in C# or the End structure in VB.NET. But one of the
most important differences between structures and classes is that structures are referenced
by value and classes by reference. As a value type, allocated on the stack, structs provide a
significant opportunity to increase program efficiency. Objects on the stack are faster to
allocate and de-allocate. A struct is a good choice for data-bound objects, which dont
require too much memory. The memory requirements should be considered based on the
fact that the size of memory available on the stack is limited than the memory available on
the heap. Thus we must use classes in situations where large objects with lots of logic are
required.

Syntax: public struct StructName


{
DataMembers
MemberFunctions
--------------}
How to Create Object
Syntax: structName ObjName;

How to Access the Members of Struct


Syntax:ObjName.Member

You might also like