You are on page 1of 6

P a g e |1

What is C#

C# is a type-safe, component-based, high-performance language that is designed for the Microsoft .NET framework. C# 2.0
is the new generation of C#, upgraded with Generics and other advanced features and fully integrated into .NET 2.0 and
Visual Studio 2005. If you are developing Windows or web applications or web services for the .NET platform, C# is in many
ways the language of choice.

Need to Write and Run C# Code

The .NET Framework 3.5 will run on Windows XP, 2003, Vista, and the latest Windows Server 2008. In order to write code
using .NET, you will need to install the .NET 3.5 SDK. Also, unless you are intending to write your C# code using a text editor
or some other third – party developer environment, you will almost certainly also want Visual Studio 2008. The full SDK isn’t
needed to run managed code, but the .NET runtime is needed. You may find you need to distribute the .NET runtime with
your code for the benefit of those clients who do not have it already installed.

Where C# Fits

In one sense, C# can be seen as being the same thing to programming languages as .NET is to the Windows environment.
Just as Microsoft has been adding more and more features to Windows and the Windows API over the past decade, Visual
Basic 2008 and C++ have undergone expansion.

In the case of Visual Basic 6 and earlier versions, the main strength of the language was the fact that it was simple to
understand and made many programming tasks easy, largely hiding the details of the Windows API and the COM
component infrastructure from the developer.

C++, on the other hand, has its roots in the ANSI C++ language definition. It isn ’ t completely ANSI - compliant for the simple
reason that Microsoft first wrote its C++ compiler before the ANSI definition had become official, but it comes close.

Now enter .NET — a completely new environment that is going to involve new extensions to both languages. Microsoft has
gotten around this by adding yet more Microsoft - specific keywords to C++, and by completely revamping Visual Basic into
Visual Basic .NET into Visual Basic 2008, a language that retains some of the basic VB syntax but that is so different in design
that it can be considered, for all practical purposes, a new language.

It ’ s in this context that Microsoft has decided to give developers an alternative — a language designed specifically for .NET,
and designed with a clean slate. C# also shares the same block structure with braces ( {} ) to mark blocks of code, and
semicolons to separate statements. The first impression of a piece of C# code is that it looks quite like C++ or Java code.
Beyond that initial similarity, however, C# is a lot easier to learn than C++, and of comparable difficulty to Java. Its design is
more in tune with modern developer tools than both of those other languages, and it has been designed to provide,
simultaneously, the ease of use of Visual Basic and the high - performance, low - level memory access of C++, if required.

Features of C#

 Full support for classes and object - oriented programming, including both interface and implementation
inheritance, virtual functions, and operator overloading.
 A consistent and well - defined set of basic types.
 Built - in support for automatic generation of XML documentation.
 Automatic cleanup of dynamically allocated memory.
 The facility to mark classes or methods with user - defined attributes. This can be useful for documentation and
can have some effects on compilation (for example, marking methods to be compiled only in debug builds).
 Full access to the .NET base class library, as well as easy access to the Windows API (if you really need it, which
won ’ t be all that often).
P a g e |2

 Pointers and direct memory access are available if required, but the language has been designed in such a way that
you can work without them in almost all cases.
 Support for properties and events in the style of Visual Basic.
 Just by changing the compiler options, you can compile either to an executable or to a library of .NET components
that can be called up by other code in the same way as ActiveX controls (COM components).
 C# can be used to write ASP.NET dynamic Web pages and XML Web services.

Sample C# Code

using System;
class MyFirstCSharpClass{
static void Main(){
Console.WriteLine("This isn’t at all like Java!");
Console.ReadLine();
return;
}
}

Compiling C# Program

You can compile this program by simply running the C# command - line compiler ( csc.exe ) against the source file, like this:

csc First.cs

If you want to compile code from the command line using the csc command, you should be aware that the .NET command -
line tools, including csc , are available only if certain environment variables have been set up. Depending on how you
installed .NET (and Visual Studio 2008), this may or may not be the case on your machine.

Most statements end in a semicolon ( ; ) and can continue over multiple lines without needing a continuation character.
Statements can be joined into blocks using curly braces ( {} ). Single - line comments begin with two forward slash
characters ( // ), and multiline comments begin with a slash and an asterisk ( /* ) and end with the same combination
reversed ( */ ). In these aspects, C# is identical to C++ and Java but different from Visual Basic. The first few lines in the
previous code example have to do with namespaces, which are a way to group together associated classes. The using
statement specifies a namespace that the compiler should look at to find any classes that are referenced in your code but
that aren’t defined in the current namespace. This serves the same purpose as the import statement in Java and the using
namespace statement in C++.

C# code must be contained within a class. Classes in C# are similar to classes in Java and C++, and very roughly comparable
to class modules in Visual Basic 6. The class declaration consists of the class keyword, followed by the class name and a pair
of curly braces. All code associated with the class should be placed between these braces. Next, you declare a method
called Main() . Every C# executable (such as console applications, Windows applications, and Windows services) must have
an entry point — the Main() method (note the capital M )

You simply call the WriteLine() method of the System.Console class to write a line of text to the console window.
WriteLine() is a static method, so you don ’ t need to instantiate a Console object before calling it. Console.ReadLine() reads
user input. Adding this line forces the application to wait for the carriage return key to be pressed before the application
exits, and, in the case of Visual Studio 2008, the console window disappears. You then call return to exit from the method
(also, because this is the Main() method, you exit the program as well.). You specified void in your method header, so you
don ’ t return any values. The return statement is equivalent to return in C++ and Java, and Exit Sub or Exit Function in
Visual Basic.
P a g e |3

Variables

You declare variables in C# using the following syntax:

datatype identifier;

For example:

int i;

This statement declares an int named i . The compiler won’t actually let you use this variable in an expression until you have
initialized it with a value. Once it has been declared, you can assign a value to the variable using the assignment operator, =:
i = 10;

You can also declare the variable and initialize its value at the same time:

int i = 10;
This syntax is identical to C++ and Java syntax but very different from Visual Basic syntax for declaring variables. The C#
syntax for declaring variables is the same no matter what the data type of the variable. If you declare and initialize more
than one variable in a single statement, all of the variables will be of the same data type:

int x = 10, y =20; // x and y are both ints

To declare variables of different types, you need to use separate statements. You cannot assign different data types within
a multiple variable declaration:

int x = 10;
bool y = true; // Creates a variable that stores true or false
int x = 10, bool y = true; // This won’t compile!

Variable Initialization

C# has two methods for ensuring that variables are initialized before use:
 Variables that are fields in a class or struct, if not initialized explicitly, are by default zeroed out when they are
created (classes and structs are discussed later).
 Variables that are local to a method must be explicitly initialized in your code prior to any statements in which
their values are used.

Type Inference

Type inference makes use of the var keyword. The syntax for declaring the variable changes somewhat. The compiler “
infers ” what the type of the variable is by what the variable is initialized to. For example,

int someNumber = 0;

becomes

var someNumber = 0;

Even though someNumber is never declared as being an int , the compiler figures this out and someNumber is an int for as
long as it is in scope. Once compiled, the two preceding statements are equal.
P a g e |4

Variable Scope

The scope of a variable is the region of code from which the variable can be accessed. In general, the scope is determined
by the following rules:

 A field (also known as a member variable) of a class is in scope for as long as its containing class is in scope (this is
the same as for C++, Java, and VB).
 A local variable is in scope until a closing brace indicates the end of the block statement or method in which it was
declared.
 A local variable that is declared in a for , while , or similar statement is in scope in the body of that loop.

Constants

As the name implies, a constant is a variable whose value cannot be changed throughout its lifetime. Prefixing a variable
with the const keyword when it is declared and initialized designates that variable as a constant:

const int a = 100;

Constants have the following characteristics:


 They must be initialized when they are declared, and once a value has been assigned, it can never be overwritten.
 The value of a constant must be computable at compile time. Therefore, you can ’ t initialize a constant with a
value taken from a variable. If you need to do this, you will need to use a read - only field (Objects and Types).
 Constants are always implicitly static. Notice that you don’t have to include the static modifier in the constant
declaration.

Predefined Data Types

C# is much stricter about the types available and their definitions than some other languages are.

Categories of data type:


 Value types
 Reference types

The difference is that a value type stores its value directly, whereas a reference type stores a reference to the value. Value
types in C# are basically the same as simple types (integer, float, but not pointers or references) in Visual Basic or C++.
Reference types are the same as reference types in Visual Basic and are similar to types accessed through pointers in C++.

These types are stored in different places in memory; value types are stored in an area known as the stack , and reference
types are stored in an area known as the managed heap . It is important to be aware of whether a type is a value type or a
reference type because of the different effect each assignment has. For example, int is a value type, which means that the
following statement will result in two locations in memory storing the value 20:

The basic predefined types recognized by C# are not intrinsic to the language but are part of the .NET Framework. For
example, when you declare an int in C#, what you are actually declaring is an instance of a .NET struct, System.Int32.

Predefined Types

Name CTS Type Description Range


sbyte System.SByte 8-bit signed integer -128:127 ( - 2 7 :2 7 - 1)
short System.Int16 16 - bit signed integer - 32,768:32,767 ( - 2 15 :2 15 - 1)
int System.Int32 32 - bit signed integer - 2,147,483,648:2,147,483,647 ( - 2 31 :2 31 - 1)
long System.Int64 64 - bit signed integer - 9,223,372,036,854,775,808:
P a g e |5

9,223,372,036,854,775,807 ( - 2 63 :2 63 - 1)
Byte System.Byte 8 - bit unsigned integer 0:255 (0:2 8 - 1)
ushort System.UInt16 16 - bit unsigned integer 0:65,535 (0:2 16 - 1)
uint System.UInt32 32 - bit unsigned integer 0:4,294,967,295 (0:2 32 - 1)
ulong System.UInt64 64 - bit unsigned integer 0:18,446,744,073,709,551,615 (0:2 64 - 1)

Escape Sequence Character

\‘ Single quotation mark


\“ Double quotation mark
\\ Backslash
\0 Null
\a Alert
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Tab character
\v Vertical tab

Literals of type char are signified by being enclosed in single quotation marks, for example ‘ A ’ . If you try to enclose a
character in double quotation marks, the compiler will treat this as a string and throw an error. You can also represent them
with an escape sequence, as shown in the following table.

Predefined Reference Types

C# supports two predefined reference types, object and string , described in the following table.

Name CTS Type Description


object System.Object The root type. All other types in the CTS are derived (including value types) from object .
string System.String Unicode character string.

The object Type

Many programming languages and class hierarchies provide a root type, from which all other objects in the hierarchy are
derived. C# and .NET are no exception. The object type is the ultimate parent type from which all other intrinsic and user -
defined types are derived. This is a key feature of C# that distinguishes it from both Visual Basic 6.0 and C++, although its
behavior here is very similar to Java. All types implicitly derive ultimately from the System.Object class. This means that you
can use the object type for two purposes:

 You can use an object reference to bind to an object of any particular subtype. You will see how you can use the
object type to box a value object on the stack to move it to the heap. Object references are also useful in
reflection, when code must manipulate objects whose specific types are unknown. This is similar to the role played
by a void pointer in C++ or by a Variant data type in VB.
 The object type implements a number of basic, general - purpose methods, which include Equals() ,
GetHashCode() , GetType() , and ToString()

C# recognizes the string keyword, which under the hood is translated to the .NET class, System .String . With it, operations
like string concatenation and string copying are a snap:
P a g e |6

string str1 = “Hello “;


string str2 = “World”;
string str3 = str1 + str2; // string concatenation

Console I/O

By this point, you should have a basic familiarity with C# ’ s data types, as well as some knowledge of how the thread - of -
control moves through a program that manipulates those data types. In this chapter, you have also used several of the
Console class ’ s static methods used for reading and writing data. Because these methods are so useful when writing basic
C# programs, this section quickly reviews them in more detail.

To read a line of text from the console window, you use the Console.ReadLine() method. This will read an input stream
(terminated when the user presses the Return key) from the console window and return the input string. There are also two
corresponding methods for writing to the console, which you have already used extensively:

 Console.Write() — Writes the specified value to the console window.


 Console.WriteLine() — This does the same, but adds a newline character at the end of the output.

Various forms (overloads) of these methods exist for all of the predefined types (including object ), so in most cases you don
’ t have to convert values to strings before you display them. For example, the following code lets the user input a line of
text and displays that text:

string s = Console.ReadLine();
Console.WriteLine(s);

Console I/O Example

using System;
namespace comp.stud
{
class MyFirstCSharpClass
{
public static void Main()
{
string j;
int n;
Console.Write("Please enter any number: ");
j = Console.ReadLine();
n = Convert.ToInt16(j) * Convert.ToInt16(j);
Console.Write("I double your number: "+n);
return;
}
}
}

You might also like