Friday, April 23, 2010

DATA TYPES IN C#


WHAT IS TYPE?

In daily usage, the word type usually signifies a number of persons or items sharing one or more particular characteristics. This often causes a group of people of the same type to be regarded as a more or less precisely defined group.In C#, all values belonging to a specific type can be used to share a set of predefined characteristics.

THE TYPES OF C#

C# is a strongly typed language.Every value in C# must have a type.There are two kinds of data types in C#.

  • Value Types(implicit data types, structs and enumeration)
  • Reference Types(objects, delegates) 

Value types are passed to methods by passing an exact copy while Reference types are passed to methods by passing only their reference (handle). Implicit data types are defined in the language core by the language vendor, while explicit data types are types that are made by using or composing implicit data types.
Implicit data types in .Net compliant languages are mapped to types in the Common Type System (CTS) and CLS (Common Language Specification). Hence, each implicit data type in C# has its corresponding .Net type. The implicit data types in C# are:






Implicit data types are represented in language using keywords, so each of the above is a keyword in C# (Keyword are the words defined by the language and can not be used as identifiers). It is worth noting that string is also an implicit data type in C#, so string is a keyword in C#. The last point about implicit data types is that they are value types and thus stored on the stack, while user defined types or referenced types are stored using the heap.

A stack is a data structure that store items in a first in first out (FIFO) fashion. It is an area of memory supported by the processor and its size is determined at the compile time. A heap consists of memory available to the program at run time. Reference types are allocated using memory available from the heap dynamically (during the execution of program). The garbage collector searches for non-referenced data in heap during the execution of program and returns that space to Operating System.

VARIABLES
During the execution of a program, data is temporarily stored in memory. A variable is the name given to a memory location holding a particular type of data. So, each variable has associated with it a data type and a value. In C#, variables are declared as:

Ex : int i;

The above line will reserve an area of 4 bytes in memory to store an integer type values, which will be referred to in the rest of program by the identifier 'i'. One can initialize the variable as declared  (on the fly) and can also declare/initialize multiple variables of the same type in a single statement,

Ex : int i = 2 ;

In C# (like other modern languages), the variables must be declared before being used. Also, there is the concept of "Definite Assignment" in C# which says "local variables (variables defined in a method) must be initialized before being used".

Constant Variables or Symbols 

Constants are variables whose values, once defined, can not be changed by the program. Constant variables are declared using the const keyword, like:

const double PI = 3.142;

Constant variables must be initialized as they are declared. It is a syntax error to write:

const int MARKS;

It is conventional to use capital letters when naming constant variables.

Thursday, April 22, 2010

C# Language Fundamentals


C# LANGUAGE FUNDAMENTALS

A computer program is the formatting and use of these words in an organized manner, along with a few additional words and symbols. The key parts of a C# language include the following:


  • Whitespace
  • Keywords
  • Literals
  • Identifiers
  • Comments
  • Operators
  • Separators
NOTE : The Keywords and Comments are discussed earlier.

Whitespace :

The blank spaces put into a listing are called whitespace. The basis of this term is that, on white paper, one can never see the spaces. Whitespace can consist of spaces, tabs, line feeds, and carriage returns.

The compiler almost always ignores whitespace. Because of this, one can add as many spaces, tabs, and line feeds as desired.
For example,

int radius = 4;


This is a well-formatted line with a single space between items. This line could have had additional spaces:


int         radius         =         4 ;

This line with extra spaces executes the same way as the original.
In fact, when the program is run through the C# compiler, the extra whitespace is removed.
One can also format this code across multiple lines:


int
radius
=
4
;


Although this is not very readable, it still works.
If the text is within double quotes. It is written exactly as it is presented between the quotation marks.

Literals :
Literals are straightforward hard-coded values. They are literally what they are!
Literals can be stored by any variable with a type compatible with that of literal.

Identifiers :

Identifiers are used to name classes, methods and variables.Another aspect related to identifiers is CAPITALIZATION STYLE.The capitalization styles used in C# world are :

Pascal Casing : The first letter of each word in the name is capitalized.Recommended for naming classes and methods.
Ex: MyNewBlog.

Camel Casing : Same as Pascal casing but the first word of identifier should be in lower case.Recommend for naming variables.
Ex: myNewBlog.

Separators :
Separators are used to separate various elements in C# from each other.
Ex: Braces - { }, Parentheses - (),  Semicolon - ; , comma - , Period or dot operator .

Operators :

Operators are represented by symbols.Operators act on operands.Ex : a+b;  '+' is an Operator.

Operators are classified as Binary Operators and Unary Operators.

Binary Operators : It combines two operands to produce the result.Ex : a+b
Unary Operators : They act only upon one operand.Ex : a++

TYPES OF OPERATORS
Assignment Operator :
The assignment operator simply assigns the result of an expression to a variable. In essence the = assignment operator takes two operands. The left hand operand is the variable to which a value is to be assigned and the right hand operand is the value to be assigned. The right hand operand is, more often than not, an expression which performs some type of arithmetic or logical evaluation.


Ex : sum = a + b  or x = 10.

Assignment operators may also be chained to assign the same value to multiple variables.

Ex : a = b = c = 100.

Arithmetic Operators :
C# provides a range of operators for the purpose of creating mathematical expressions. These operators primarily fall into the category of binary operators in that they take two operands.


The following table lists the primary C# arithmetic operators:

OperatorDescription
-(unary)Negates the value of a variable or expression
*Multiplication
/Division
+Addition
-Subtraction
%Modulo

Multiple Operators may be used in a single expression.

Ex : z = a + b - c * d / e.

Operator Precedence :

All operators are not treated equally. There is a concept of "operator precedence" in C#.The following table outlines the C# operator precedence order from highest precedence to lowest:


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

* / %

+ -

<< >>

< > <= >= is as

==  !=

&

^

|

&&

||

:?
Lowest= *= /= %= += -= <<= >>= &= ^= |=

NOTE :  The assignment operators have the lowest precedence.


Numerous compound assignment operators are available in C#. The most frequently used are outlined in the following table:

OperatorDescription
x += yAdd x to y and place result in x
x -= ySubtract y from x and place result in x
x *= yMultiply x by y and place result in x
x /= yDivide x by y and place result in x
x %= yPerform Modulo on x and y and place result in x
x &= yAssign to x the result of logical AND operation on x and y
x |= yAssign to x the result of logical OR operation on x and y
x ^= yAssign to x the result of logical Exclusive OR on x and y

Increment and Decrement Operators :
++ is an Increment Operator and -- is a decrement Operator.
The usage of these operators makes them different like Prefix and Postfix notation.

Prefix Notation :B =  ++a.This means increment by 1 first then assign it to B.
Postfix Notation : B = a++.This means first assign then increment  by 1.

Comparision Operator :


In addition to mathematical and assignment operators, C# also includes set of logical operators useful for performing comparisons. These operators all return a Boolean (bool) true or false result depending on the result of the comparison.

These operators are binary in that they work with two operands.
Comparison operators are most frequently used in constructing program flow control. The following table lists the full set of C# comparison operators:


OperatorDescription
x == yReturns true if x is equal to y
x > yReturns true if x is greater than y
x >= yReturns true if x is greater than or equal to y
x < yReturns true if x is less than y
x <= yReturns true if x is less than or equal to y
x != yReturns true if x is not equal to y

Logical  and Bitwise Operators :

These operators are used for logical and bitwise calculations. Common logical and bitwise operators in C# are:
Operand            Description
&                       Bitwise AND
|                         Bitwise OR
^                        Bitwise XOR
!                         Bitwise NOT
&&                     Logical AND
||                        Logical OR

The operators &, | and ^ are rarely used in usual programming practice. The NOT operator is used to negate a Boolean or bitwise expression.

The Ternary Operator :

C# uses something called a ternary operator to provide a shortcut way of making decisions. The syntax of the ternary operator is as follows:

[condition] ? [true expression] : [false expression]

Ex : Z = x > y ? x : y ;


if x is greater than y then x is returned else, y is returned.

Tuesday, April 20, 2010

Introduction to C#



Introduction to C#

C# (pronounced C-Sharp) is a powerful and flexible programming language.Like all other programming languages, it is used to create a variety applications.
C# is an Object Oriented Programming language and has at its core, many similarities to Java, C++ and VB.In fact, C# combines the power and efficiency of C++, the simple and clean OO design of Java and the language simplification of Visual Basic.

C# removes some of the complexities and pitfalls of languages such as Java and C++.C# also does not allow multiple inheritance or the use of pointers (in safe/managed code), but does provide garbage memory collection at runtime, type and memory access checking. However, contrary to JAVA, C# maintains the unique useful operations of C++ like operator overloading, enumerations, pre-processor directives, pointers (in unmanaged/un-safe code), function pointers (in the form of delegates) and promises to have template support in the next versions.

From the above discussion, objectives of C# can be summarized as :





  • Simple
  • Modern
  • Modular
  • Object-oriented
  • Powerful and flexible
  • A Language of few words

C# is simple and modern because of its extensive features like garbage collection, extensible data types and exception handling.
It is powerful and flexible because it is limited by your imagination.
It is a language of few words ,constants also called as
Keywords which serves the built-in functionality.
Keywords, also known as
reserved words, are tokens that have special meaning in a language. The Keywords of C# are listed below :


abstractevent new struct
as explicitnull switch
base externobject this
boolfalse operatorthrow
breakfinally outtrue
bytefixed overridetry
casefloat paramstypeof
catchfor privateuint
charforeach protectedulong
checkedgoto publicunchecked
classif readonlyunsafe
constimplicit refushort
continuein return using
decimal intsbyte virtual
default interfacesealed volatile
delegate internalshort void
do issizeof while
doublelock stackalloc
else longstatic
enumnamespace string

COMMENTS IN C# 

C# Coding Style is used to robust and reliable programs.Comments are the programmer's text to explain the code, are ignored by the compiler and are not included in the final executable code. C# uses syntax for comments that is similar to Java and C++. The comment ends with the end of the line. 

Block comments:

Block comments should usually be avoided. For descriptions use of the /// comments to give C# standard descriptions is recommended. Block comments can be used in the following style :


/* Line 1
* Line 2
* Line 3
*/

Alternatively oldfashioned C style single line comments, even though it is not recommended.

/* blah blah blah */



Single Line Comments:

These are used for commenting sections of code too.

//Single comment
A rule of thumb says that generally, the length of a comment should not exceed the length of the code explained by too much, as this is an indication of too complicated, potentially buggy, code.



THE PROGRAM-DEVELOPMENT LIFE CYCLE

The program-development cycle has its own steps. In the first step, you use an editor to create a file that contains your source code. In the second step, you compile the source code to create an intermediate file called either an executable file or a library file. The third step is to run the program to see whether it works as originally planned.
 

Creating The Source Code:



Source code is a series of statements or commands used to instruct the computer
to perform your desired tasks. These statements and commands are a set of key- words that have special meaning along with other text. As a whole, this text is readable and understandable.

Here is a snippet of C# source code:

System.Console.WriteLine(“
Hello, Blogger!”);

This line of source code writes
Hello Blogger!

Using An Editor :

An editor is a program that can be used to enter and save source code. A number of editors can be used with C#. Some are made specifically for C#, and others are not.Microsoft has added C# capabilities to Microsoft Visual Studio .NET, which now includes Microsoft Visual C# .NET. This is the most prominent editor available for C# programming.

If you don’t have a C# editor, don’t feel bad. Most computer systems include a program that can be used as an editor. If you’re using Microsoft Windows, you can use either Notepad or WordPad as your editor. If you’re using a Linux or UNIX system, you can use such editors as ed, ex, edit, emacs, or vi.
 



Naming Your Source Files :

The name should describe what the program does. Although you could give your source file any extension, .cs is recog- nized as the appropriate extension to use for a C# program source file.


Understanding the Execution of a C# Program


C# programs are created to run on the .NET Common Language Runtime (CLR). This means that if you create a C# executable program and try to run it on a machine that doesn’t have the CLR or a compatible runtime, the program won’t execute.With C#, we create only one executable program, and it runs on either machine.

C# compiler produces an Intermediate Language (IL) file. This IL file can be copied to any machine with a .NET CLR.The CLR or a compatible C# runtime does this final compile just as it is needed.Compiling the program is one of the first things the CLR does with an IL file. In this process, the CLR converts the code from the portable, IL code to a language (machine language) that the computer can understand and run. The CLR actually compiles only the parts of the program that are being used. This saves time. This final compile of a C# pro- gram is called Just In Time (JIT) compiling, or jitting.


Compiling C# Source code to Intermediate Language
 



C# compiler is used to create the IL file.For Microsoft .NET Framework SDK,  the csc command is used, followed by the name of the source file, to run the compiler. For example, to compile a source file called Blogger.cs, you type the following at the command line:

csc Blogger.cs

For other frameworks like  mono whose compiler is mcs can be compiled as :

mcs Blogger.cs

For graphical development environment such as Microsoft Visual C# .NET, compiling is even simpler. In most graphical environments, compile a program by selecting the Compile icon or selecting the appropriate option from the menu. After the code is compiled, selecting the Run icon or the appropriate option from the menus executes the program.



NOTE :
After a program is compiled, an IL file is generated. If you look at a list of the files in the
directory or folder in which you compiled, you should find a new file that has the same name as your source file, but with an .exe (rather than a .cs) extension. The file with the .exe extension is your compiled program (called an
assembly). This program is ready to run on the CLR. The assembly file contains all the information that the CLR needs to know to execute the program. According to .NET terminology, the code inside the assembly file is called managed code.


Completing the Development Cycle
 



A compiled IL file can be run by entering its name at the command-line prompt or just by Run in any other program. However, the program requires a .NET CLR. If the CLR is not installed,an error will be generated when you run the program. Installing the Microsoft .NET Framework allows to run the programs like all other programs. For other frameworks,something different is to be done. For example, when using the mono compiler (mcs), the program can be run by entering it after mono. For example, to run the Blogger program mentioned earlier, you would type the following at the command line:

mono Blogger.exe


Steps to Write a Simple C# Program
 


Possibly download and install the free Microsoft .NET SDK or Visual Studio.Net.After the .NET SDK is installed successfully,  follow these simple steps :


  • Choose a Text Editor and type the program in command console.
  • Save the file with the .cs extension.
  • Compile the Code
  • If compiled successfully, a file with .exe extension is created in the same folder.
  • Run the program.
  • Verify that the output matches the desired one.


Create Your First C# Program


class Blogger
{
      public static void Main()
      {
             System.Console.WriteLine(“Hello, Blogger!”);
       }
}



Output :
Hello, Blogger!