You are on page 1of 77

PROJECT IN SPL

SUBMITTED BY : CHARLYN T. CASTRO RINA LYN P. ENCINA CT-23

MS.AGUSTIN

History :
During the development of the .NET Framework, the class libraries were originally written using a managed code compiler system called Simple Managed C (SMC).[12][13][14] In January 1999, Anders Hejlsberg formed a team to build a new language at the time called Cool, which stood for "C-like Object Oriented Language".[15] Microsoft had considered keeping the name "Cool" as the final name of the language, but chose not to do so for trademark reasons. By the time the .NET project was publicly announced at the July 2000 Professional Developers Conference, the language had been renamed C#, and the class libraries and ASP.NET runtime had been ported to C#. C#'s principal designer and lead architect at Microsoft is Anders Hejlsberg, who was previously involved with the design of Turbo Pascal, Embarcadero Delphi (formerly CodeGear Delphi and Borland Delphi), and Visual J++. In interviews and technical papers he has stated that flaws[citation needed] in most major programming languages (e.g. C++, Java, Delphi, and Smalltalk) drove the fundamentals of the Common Language Runtime (CLR), which, in turn, drove the design of the C# language itself. James Gosling, who created the Java programming language in 1994, and Bill Joy, a co-founder of Sun Microsystems, the originator of Java, called C# an "imitation" of Java; Gosling further claimed that "[C# is] sort of Java with reliability, productivity and security deleted."[3][16] Klaus Kreft and Angelika Langer (authors of a C++ streams book) stated in a blog post that "Java and C# are almost identical programming languages. Boring repetition that lacks innovation," "Hardly anybody will claim that Java or C# are revolutionary programming languages that changed the way we write programs," and "C# borrowed a lot from Java - and vice versa. Now that C# supports boxing and unboxing, we'll have a very similar feature in Java." [17] Anders Hejlsberg has argued that C# is "not a Java clone" and is "much closer to C++" in its design. [18] Since the release of C# 2.0 in November 2005, the C# and Java languages have evolved on increasingly divergent trajectories, becoming somewhat less similar. One of the first major departures came with the addition of generics to both languages, with vastly different implementations. C# makes use of reification to

provide "first-class" generic objects that can be used like any other class, with code generation performed at class-load time.[19] By contrast, Java's generics are essentially a language syntax feature, and they do not affect the generated byte code, because the compiler performs type erasure on the generic type information after it has verified its correctness.[20] Furthermore, C# has added several major features to accommodate functional-style programming, culminating in their LINQ extensions released with C# 3.0 and its supporting framework of lambda expressions, extension methods, and anonymous classes.[21] These features enable C# programmers to use functional programming techniques, such as closures, when it is advantageous to their application. The LINQ extensions and the functional imports help developers reduce the amount of "boilerplate" code that is included in common tasks like querying a database, parsing an xml file, or searching through a data structure, shifting the emphasis onto the actual program logic to help improve readability and maintainability.[22] C# used to have a mascot called Andy (named after Anders Hejlsberg). It was retired on 29 Jan 2004.[23] C# was originally submitted for review to the ISO subcommittee JTC 1/SC 22[24] under ISO/IEC 23270:2003,[25] which is now withdrawn. It was then approved under ISO/IEC 23270:2006.[26]

Name
C-sharp musical note (left) The name "C sharp" was inspired by musical notation where a sharp indicates that the written note should be made a semitone higher in pitch.[7] This is similar to the language name of C++, where "++" indicates that a variable should be incremented by 1. Due to technical limitations of display (standard fonts, browsers, etc.) and the fact that the sharp symbol (U+266F music sharp sign (HTML: ♯)) is not present on the standard keyboard, the number sign (U+0023 # number sign (HTML: #)) was chosen to represent the sharp symbol in the written name of

the programming language.[8] This convention is reflected in the ECMA-334 C# Language Specification.[6] However, when it is practical to do so (for example, in advertising or in box art [9]), Microsoft uses the intended musical symbol. The "sharp" suffix has been used by a number of other .NET languages that are variants of existing languages, including J# (a .NET language also designed by Microsoft that is derived from Java 1.1), A# (from Ada), and the functional programming language F#.[10] The original implementation of Eiffel for .NET was called Eiffel#,[11] a name since retired since the full Eiffel language is now supported. The suffix has also been used for libraries, such as Gtk# (a .NET wrapper for GTK+ and other GNOME libraries), Cocoa# (a wrapper for Cocoa) and Qt# (a .NET language binding for the Qt toolkit).

To compile your first C# application, you will need a copy of a .NET Framework SDK installed on your PC.T There are two .NET frameworks available: Microsoft's and Mono's. Microsoft For Windows, the .Net Framework SDK can be downloaded from Microsoft's .NET Framework Developer Center. If the default Windows directory (the directory where Windows or WinNT is installed) is C:\WINDOWS, the .Net Framework SDK installation places the Visual C# .NET Compiler (csc) in the C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705 directory for version 1.0, the C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322 directory for version 1.1, or the C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 directory for version 2.0. Mono For Windows, Linux, or other Operating Systems, an installer can be downloaded from the Mono website. For Linux, a good compiler is cscc which can be downloaded for free from the DotGNU Portable.Net project page. The compiled programs can then be run with ilrun. If you are working on Windows it is a good idea to add the path to the folders that contain cs.exe or mcs.exe to the Path environment variable so that you do not need to type the full path each time you want to compile. For writing C#.NET code, there are plenty of editors that are available. It's entirely possible to write C#.NET programs with a simple text editor, but it should be noted that this requires you to compile the code yourself. Microsoft offers a wide range of code editing programs under the Visual Studio line that offer syntax highlighting as well as compiling and debugging capabilities. Currently C#.NET can be compiled in Visual Studio 2002 and 2003 (only supports the .NET Framework version 1.0 and 1.1) and Visual Studio 2005 (supports the .NET Framework 2.0 and earlier versions with some tweaking). Microsoft offers five Visual Studio editions, four of which cost money. The Visual Studio C# Express Edition can be downloaded and used for free from Microsoft's website.

The code below will demonstrate a C# program written in a simple text editor. Start by saving the following code to a text file called hello.cs: using System; namespace MyConsoleApplication { class MyFirstClass { static void Main(string[] args) { System.Console.WriteLine("Hello,"); Console.WriteLine("World!"); Console.ReadLine(); Alternatively, in Visual C# express, you could just hit F5 or the green play button to run the code, even though that is for debugging. Running hello.exe will produce the following output: Hello, World! The program will then wait for you to strike 'enter' before returning to the command prompt. Note that the example above includes the System namespace via the using keyword. That inclusion allows direct references to any member of the System namespace without specifying its fully qualified name. The first call to the WriteLine method of the Console class uses a fully qualified reference. System.Console.WriteLine("Hello,");

The second call to that method shortens the reference to the Console class by taking advantage of the fact that the System namespace is included (with using System). Console.WriteLine("World!"); C# is a fully object-oriented language. The following sections explain the syntax of the C# language as a beginner's course for programming in the language. Note that much of the power of the language comes from the classes provided with the .Net framework, which are not part of the C# language syntax } } } To compile hello.cs, run the following from the command line: For standard Microsoft installations of .Net 2.0, run C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe hello.cs

For Mono run mcs hello.cs.


For users of cscc, compile with "cscc -o <name>.exe <name>.cs".

Doing so will produce hello.exe. The following command will run hello.exe: On Windows, use hello.exe.

On Linux, use mono hello.exe or "ilrun <name>.exe".

ENVIRONMENT OF CSHARPED

Summary of versions C# 2.0 C# 3.0 C# 4.0 C# 5.0 (planned)[27] Future

Features added

Generics Partial types Anonymous methods Iterators Nullable types Private setters (properties) Method group conversions (delegates)

Implicitly typed local variables Object and collection initializers Auto-Implemented properties Anonymous types Extension methods Query expressions Lambda expressions Expression trees

Dynamic binding Named and optional arguments Generic co- and contravariance

Windows Runtime support Compiler-as-aAsynchronous service("Roslyn") methods Caller info attributes

Distinguishing 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 features of C# that distinguish it from C and C++ (and Java, where noted) are: It has 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[which?]. C# supports a strict Boolean data type, 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 well-defined null value; it is impossible to obtain a reference to a "dead" object (one that 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 that 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#, like C++, but unlike Java, supports operator overloading. C# is more type safe than C++. The only implicit conversions by default are those that are considered safe, such as widening of integers. This is enforced at compile-time, during JIT, and, in some cases, at runtime. No implicit conversions occur 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. Starting with version 4.0, C# supports a "dynamic" data type that enforces type checking at runtime only.

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. 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.[28] Though primarily an imperative language, since C# 3.0 it supports functional programming techniques through first-class function objects and lambda expressions.

Variables
are used to store values. More technically, a variable binds an object (in the general sense of the term, i.e. a specific value) to an identifier (the variable's name) so that the object can be accessed later. Variables can, for example, store a value for later use: string name = "Dr. Jones"; Console.WriteLine("Good morning " + name); In this example "name" is the identifier and "Dr. Jones" is the value that we bound to it. Also, each variable is declared with an explicit type. Only values whose types are compatible with the variable's declared type can be bound to (stored in) the variable. In the above example we stored "Dr. Jones" into a variable of the type string. This is a legal statement. However, if we had said int name = "Dr. Jones", the compiler would have thrown an error telling us that you cannot implicitly convert between int and string. There are methods for doing this, but we will talk about them later.

Parameter
Parameters are variables associated with a method. An in parameter may either have its value passed in from the caller to the method's environment, so that changes to the parameter by the method do not affect the value of the caller's variable, or passed in by reference, so that changes to the variables will affect the value of the caller's variable. Value types (int, double, string) are passed in "by value" while reference types (objects) are passed in "by reference." Since this is the default for the C# compiler, it is not necessary to use . An out parameter does not have its value copied, thus changes to the variable's value within the method's environment directly affect the value from the caller's environment. Such a variable is considered by the compiler to be unbound upon method entry, thus it is illegal to reference an out parameter before assigning it a value. It also must be assigned by the method in each valid (non-exceptional) code path

through the method in order for the method to compile. A reference parameter is similar to an out parameter, except that it is bound before the method call and it need not be assigned by the method. A params parameter represents a variable number of parameters. If a method signature includes one, the params argument must be the last argument in the signature. // Each pair of lines is what the definition of a method and a call of a // method with each of the parameters types would look like. // In param: void MethodOne(int param1) // definition MethodOne(variable); // call // Out param: void MethodTwo(out string message) // definition MethodTwo(out variable); // call // Reference param; void MethodThree(ref int someFlag) // definition MethodThree(ref theFlag) // call // Params void MethodFour(params string[] names) // definition MethodFour("Matthew", "Mark", "Luke", "John"); // call

Types
Each type in C# is either a value type or a reference type. C# has several predefined ("built-in") types and allows for declaration of custom value types and reference types. There is a fundamental difference between value types and reference types: Value types are allocated on the stack, whereas reference types are allocated on the heap.

Value types
The value types in the .NET framework are usually small, frequently used types. The benefit of using them is that the type requires very little resources to get up and running by the CLR. Value types do not require memory to be allocated on the heap and therefore will not cause garbage collection. However, in order to be useful, the value types (or types derived from it) should remain small - ideally below 16 bytes of data. If you choose to make your value type bigger.

CHARACTER ESCAPE SEQUENCES


Escape Sequence \' \" \\ \0 \a \b \f \n \r \t \v

Meaning Single Quote Double Quote Backslash Null, not the same as the C# null value Bell Backspace form Feed Newline Carriage Return Horizontal Tab Vertical Tab

Another useful feature of C# strings is the verbatim literal, which is a string with a @ symbol prefix, as in @"Some string". Verbatim literals make escape sequences translate as normal characters to enhance readability. To appreciate the value of verbatim literals, consider a path statement such as "c:\\topdir\\subdir\\subdir\\myapp.exe". As you can see, the backslashes are escaped, causing the string to be less readable. You can improve the string with a verbatim literal, like this: @"c:\topdir\subdir\subdir\myapp.exe". That is fine, but now you have the problem where quoting text is not as easy. In that case, you would specify double double quotes. For example, the string "copy \"c:\\source file name with spaces.txt\" c:\\newfilename.txt" would be written as the verbatim literal @"copy ""c:\source file name with spaces.txt"" c:\newfilename.txt".

OPERATORS WITH THEIR PRECEDENCE AND ASSOCIATIVITY


Category (by precedence) Primary Unary Multiplicative Additive Shift Relational Equality Logical AND Logical XOR Logical OR Conditional AND Conditional OR Null Coalescing Ternary Assignment Operator(s) Associativity x.y f(x) a[x] x++ x-new typeof default checked un left checked delegate + - ! ~ ++x --x (T)x right * / % left + left << >> left < > <= >= is as left == != right & left ^ left | left && left || left ?? left ?: right = *= /= %= += right = <<= >>= &= ^= |= =>

Double and Float Variables in C#


Integers, as was mentioned, are whole numbers. They can't store the point something, like .7, .42, and .007. If you need to store numbers that are not whole numbers, you need a different type of variable. You can use the double type, or the float type. You set these types of variables up in exactly the same way: instead of using the word int, you type double, or float. Like this: float myFloat; double myDouble; (Float is short for "floating point", and just means a number with a point something on the end.) The difference between the two is in the size of the numbers that they can hold. For float, you can have up to 7 digits in your number. For doubles, you can have up to 16 digits. To be more precise, here's the official size: float: 1.5 10-45 to 3.4 1038 double: 5.0 10-324 to 1.7 10308 Float is a 32-bit number and double is a 64-bit number. To get some practice using floats and doubles, return to your form. If you can't see the Form1.cs [Design] tab at the top, right click Form1.cs in the Solution Explorer on the right hand side. (If you can't see the Solution Explorer, click View > Solution Explorer from the menu bar at the top.)

Add a new button to your form. Set the following properties for it in the Properties Window: Name btnFloat Location: 110, 75 Text: Float Double click your new button, and add the following line to the button code: float myFloat; Your coding window will then look like this:

To store something inside of your new variable, add the following line: myFloat = 0.42F; The capital letter F on the end means Float. You can leave it off, but C# then treats it like a double. Because you've set the variable up as a float, you'll get errors if you try to assign a double to a float variable. Add a third line of code to display your floating point number in a message box: MessageBox.Show( myFloat.ToString( ) ); Again, we have to use ToString( ) in order to convert the number to a string of text, so that the message box can display it. But your coding window should look like ours below:

Run your programme and click your Float button. You should see a form like this:

Halt the programme and return to your coding window. Now delete the capital letter F from 0.42. The line will then be: myFloat = 0.42; Try to run your programme again. You'll get an error message, and a blue wiggly line under your code. Because you've missed the F out, C# has defaulted to using a double value for your number. A float variable can't hold a double value, confirming that C# is a strongly typed language. (The opposite is a weakly typed language. PHP, and JavaScript are examples of weakly typed languages - you can store any kind of values in the variables you set up.) Another thing to be careful of when using float variables is rounding up or down. As an example, change the number from 0.42F to 1234.567F. Now run your programme, and click your float button. The message box will be this:

Halt the programme and return to your code. Now add an 8 before the F and after the 7, so that your line of code reads: myFloat = 1234.5678F; Now run your programme again. When you click the button, your message box will be this:

Common type system


C# has a unified type system. This unified type system is called Common Type System (CTS).[29] A unified type system implies that all types, including primitives such as integers, are subclasses of the System.Object class. For example, every type inherits a ToString() method. Categories of data types CTS separates data types into two categories:[29] Value types Reference types Instances of value types do not have referential identity nor 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 all 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.

Boxing and unboxing


Boxing is the operation of converting a value of a value type into a value of a corresponding reference type.[29] Boxing in C# is implicit. Unboxing is the operation of converting a value of a reference type (previously boxed) into a value of a value type.[29] Unboxing in C# requires an explicit type cast. A boxed object of type T can only be unboxed to a T (or a nullable T).[30]

Example: int foo = 42; // Value type. object bar = foo; // foo is boxed to bar. int foo2 = (int)bar; // Unboxed back to value type.

Generics
Generics were added to version 2.0 of the C# language. Generics use type parameters, which make it possible to design classes and methods that do not specify the type used until the class or method is instantiated. The main advantage is that one can use generic type parameters to create classes and methods that can be used without incurring the cost of runtime casts or boxing operations, as shown here

// Declare the generic class. public class GenericList<T> { void Add(T input) { } } class TestGenericList { private class ExampleClass { } static void Main() { // Declare a list of type int. GenericList<int> list1 = new GenericList<int>(); // Declare a list of type string. GenericList<string> list2 = new GenericList<string>(); // Declare a list of type ExampleClass. GenericList<ExampleClass> list3 = new GenericList<ExampleClass>(); } }

Preprocessor
C# features "preprocessor directives"[32] (though it does not have an actual preprocessor) based on the C preprocessor that allow programmers to define symbols, but not macros. Conditionals such as #if, #endif, and #else are also provided. Directives such as #region give hints to editors for code folding. public class Foo { #region Constructors public Foo() {} public Foo(int firstParam) {} #endregion #region Procedures public void IntBar(int firstParam) {} public void StrBar(string firstParam) {} public void BoolBar(bool firstParam) {} #endregion }

Code comments
C# utilizes a double forward slash (//) to indicate the rest of the line is a comment. This is inherited from C++. public class Foo { // a comment public static void Bar(int firstParam) {} // also a comment } Multi-line comments can be indicated by a starting forward slash/asterisk (/*) and ending asterisk/forward slash (*/). This is inherited from standard C. public class Foo { /* A Multi-Line comment */ public static void Bar(int firstParam) {} }

Libraries
The C# specification details a minimum set of types and class libraries that the compiler expects to have available. In practice, C# is most often used with some implementation of the Common Language

Accessing members
Members of an instance and static members of a class are accessed using the . operator. Accessing an instance member Instance members can be accessed through the name of a variable. string foo = "Hello"; string fooUpper = foo.ToUpper(); Modifiers are keywords used to modify declarations of types and type members. Most notably there is a sub-group containing the access modifiers. Class modifiers abstract - Specifies that a class only serves as a base class. It must be implemented in an inheriting class. sealed - Specifies that a class cannot be inherited. Class member modifiers const - Specifies that a variable is a constant value that has to be initialized when it gets declared. event - Declares an event. extern - Specify that a method signature without a body uses a DLL-import. override - Specify that a method or property declaration is an override of a virtual member or an implementation of a member of an abstract class. readonly - Declare a field that can only be assigned values as part of the declaration or in a constructor in the same class. unsafe - Specifies an unsafe context, which allows the use of pointers. virtual - Specifies that a method or property declaration can be overridden by a derived class. volatile - Specifies a field which may be modified by an external process and prevents an optimizing compiler from modifying the use of the field.

Variables are used to store values. More technically, a variable binds an object (in the general sense of the term, i.e. a specific value) to an identifier (the variable's name) so that the object can be accessed later. Variables can, for example, store the value of user input:V string name = Console.ReadLine(); Console.WriteLine ( "Good morning, {0}" , name ); Each variable is declared with an explicit type. Only values whose types are compatible with the variable's declared type can be bound to (stored in) the variable. Fields, Local Variables, and Parameters C# supports several program elements corresponding to the general programming concept of variable: fields, parameters, and local variables. Fields Fields, sometimes called class-level variables, are variables associated with classes or structures. An instance variable is a field associated with an instance of the class or structure, while a static variable, declared with the static keyword, is a field associated with the type itself. Fields can also be associated with their class by making them constants (const), which requires a declaration assignment of a constant value and prevents subsequent changes to the field. Each field has a visibility of public, protected, internal, protected internal, or private (from most visible to least visible). Local variables Like fields, local variables can optionally be constant (const). Constant local variables are stored in the assembly data region, while non-constant local variables are stored (or referenced from) the stack. They thus have both a scope and an extent of the method or statement block that declares them.

Parameter Parameters are variables associated with a method. An in parameter may either have its value passed in from the callee to the method's environment, so that changes to the parameter by the method do not affect the value of the callee's variable, or passed in by reference, so that changes to the variables will affect the value of the callee's variable. Value types (int, double, string) are passed in "by value" while reference types (objects) are passed in "by reference." An out parameter does not have its value copied, thus changes to the variable's value within the method's environment directly affect the value from the callee's environment. Such a variable is considered by the compiler to be unbound upon method entry, thus it is illegal to reference an out parameter before assigning it a value. It also must be assigned by the method in each valid (non-exceptional) code path through the method in order for the method to compile. A reference parameter is similar to an out parameter, except that it is bound before the method call and it need not be assigned by the method. A params parameter represents a variable number of parameters. If a method signature includes one, the params argument must be the last argument in the signature. Types Each type in C# is either a value type or a reference type. C# has several predefined ("built-in") types and allows for declaration of custom value types and reference types. Integral types Because the type system in C# is unified with other languages that are CLI-compliant, each integral C# type is actually an alias for a corresponding type in the .NET framework. Although the names of the aliases vary between .NET languages, the underlying types in the .NET framework remain the same. Thus, objects created in assemblies written in other languages of the .NET Framework can be bound to C#

variables of any type to which the value can be converted, per the conversion rules below. The following illustrates the cross-language compatibility of types by comparing C# code with the equivalent Visual Basic .NET code: // C# public void UsingCSharpTypeAlias() { int i = 42; } public void EquivalentCodeWithoutAlias() { System.Int32 i = 42; } ' Visual Basic .NET Public Sub UsingVisualBasicTypeAlias() Dim i As Integer = 42 End Sub Public Sub EquivalentCodeWithoutAlias() Dim i As System.Int32 = 42 End Sub Using the language-specific type aliases is often considered more readable than using the fully-qualified .NET Framework type names. The fact that each C# type corresponds to a type in the unified type system gives each value type a consistent size across platforms and compilers. That consistency is an important distinction from other languages such as C, where, e.g. a long is only guaranteed to be at least as large as an int, and is implemented with different sizes by different compilers. As reference types, variables of types derived from object (i.e. any class) are exempt from the consistent size requirement. That is, the size of reference types like System.IntPtr, as opposed to value types like System.Int, may vary by platform. Fortunately, there is rarely a need to know the actual size of a reference type.

int i = 97; string s = i.ToString(); // The value of s is now the string "97". Likewise, the System.Int32 type implements the Parse() method, which can therefore be accessed via C#'s int type: string s = "97"; int i = int.Parse(s); // The value of i is now the integer 97. The unified type system is enhanced by the ability to convert value types to reference types (boxing) and likewise to convert certain reference types to their corresponding value types (unboxing): object boxedInteger = 97; int unboxedInteger = (int)boxedInteger; The built-in C# type aliases and their equivalent .NET Framework types follow: IntegersC# Alias .NET Type Size (bits) Range sbyte System.SByte 8 -128 to 127 byte System.Byte 8 0 to 255 short System.Int16 16 -32,768 to 32,767 ushort System.UInt16 16 0 to 65,535 char System.Char 16 A unicode character of code 0 to 65,535 int System.Int32 32 -2,147,483,648 to 2,147,483,647 uint System.UInt32 32 0 to 4,294,967,295 long System.Int64 64 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 ulong System.UInt64 64 0 to 18,446,744,073,709,551,615

Floating-pointC# Alias .NET Type float System.Single double System.Double decimal System.Decimal Other predefined typesC# Alias bool System.Boolean object System.Object string System.String

Size (bits) 32 64 128

Precision Range 7 digits 1.5 x 10-45to 3.4 x 1038 15-16 digits 5.0 x 10-324to 1.7 x 10308 28-29 decimal places 1.0 x 10-28to 7.9 x 1028

.NET Type Size (bits) Range 32 true or false, which aren't related to any integer in C#. 32/64 Platform dependant (a pointer to an object). 16 * length A unicode string with no special upper bound.

Custom types The predefined types can be aggregated and extended into custom types. Custom value types are declared with the struct or enum keyword. Likewise, custom reference types are declared with the class keyword. Arrays Although the number of dimensions is included in array declarations, the size of each dimension is not: string[] s ; Assignments to an array variable (prior to the variable's usage), however, specify the size of each dimension: s = new string[5] ; As with other variable types, the declaration and the initialization can be combined: string[] s = new string[5] ; It is also important to note that like in Java, arrays are passed by reference, and not passed by value. For example, the following code snippet successfully swaps two elements in an integer array: static void swap (int[] arr, int i, int j) {

CONTROL STRUCTURE C# inherits most of the control structures of C/C++ and also adds new ones like the foreach statement. Conditional structures These structures control the flow of the program through given conditions. if statement The if statement is entered when the given condition is true. Single-line case statements do not require block braces although it is mostly preferred by convention. if (i == 3) ... ; Multi-line with else-block (without any braces): if (i == 2) ... else ... Recommended coding conventions for an if-statement. if (i == 3) { ... } else if (i == 2) { ... } else { ... } Simple one-line statement: switch statement The switch construct serves as a filter for different values. Each value leads to a "case". It is not allowed to fall through cases and therefore the keyword break is typically used to end a case. An unconditional return in a "case" block can also be used to end a case. See also how goto statement can be used to fall through from one case to the next. Many cases may lead to the same code though. The default case handles all the other cases not handled by the construct. switch (ch) { case 'A': statement; ... break; case 'B': statement; break; case 'C': ... break; default: ... break; }

Iteration structures Iteration statements are statements that are repeatedly executed when a given condition is evaluated as true. while loop while (i == true) { ... } do ... while loop do { ... } while (i == true);

for loop The for loop consists of three parts: declaration, condition and increment. Any of them can be left out as they are optional. for (int i = 0; i < 10; i++) { ... } Is equivalent to this code represented with a while statement. int i = 0; while (i < 10) { //... i++; } foreach loop The foreach statement is derived from the for statement and makes use of a certain pattern described in C#'s language specification in order to obtain and use an enumerator of elements to iterate over. Each item in the given collection will be returned and reachable in the context of the code block. When the block has been executed the next item will be returned until there are no items remaining. foreach (int i in intList) { ... }

Jump statements Jump statements are inherited from C/C++ and ultimately assembly languages through it. They simply represent the jump-instructions of an assembly language that controls the flow of a program. Labels and goto statement Labels are given points in code that can be jumped to by using the goto statement. start: ... goto start; The goto statement can be used in switch statements to jump from one case to another or to fall through from one case to the next. switch(n) { case 1: Console.WriteLine("Case 1"); break; case 2: Console.WriteLine("Case 2"); goto case 1; case 3: Console.WriteLine("Case 3"); case 4: // Compilation will fail here as cases cannot fall through in C#. Console.WriteLine("Case 4"); goto default; // This is the correct way to fall through to the next case. default: Console.WriteLine("Default"); }

break statement The break statement breaks out of the closest loop or switch statement. Execution continues in the statement after the terminated statement, if any. int e = 10; for (int i = 0; i < e; i++) { while (true) { break; } // Will break to this point. }
continue statement The continue statement discontinues the current iteration of the current control statement and begins the next iteration. int ch; while ((ch = GetChar()) >= 0) { if (ch == ' ') continue; // Skips the rest of the while-loop // Rest of the while-loop ... }

The while loop in the code above reads characters by calling GetChar(), skipping the statements in the body of the loop if the characters are spaces. Exception handling Runtime exception handling method in C# is inherited from Java and C/C++. The base class library has a class called System.Exception from which all other exception classes are derived. An Exception-object contains all the information about a specific exception and also the inner exceptions that were caused. Programmers may define their own exceptions by deriving from the Exception class. An exception can be thrown this way: throw new NotImplementedException(); try ... catch ... finally statements Exceptions are managed within try ... catch blocks. try { // Statements which may throw exceptions ... } catch (Exception ex) { // Exception caught and handled here ... } finally { // Statements always executed after the try/catch blocks ... } The statements within the try block are executed, and if any of them throws an exception, execution of the block is discontinued and the exception is handled by the catch block. There may be multiple catch blocks, in which case the first block with an exception variable whose type matches the type of the thrown exception is executed. If no catch block matches the type of the thrown exception, the execution of the outer block (or method) containing the try ... catch statement is discontinued, and the exception is passed up and outside the containing block or method. The exception is propagated upwards through the call stack until a matching catch block is found within one of the currently active methods. If the exception propagates all the way up to the top-most Main() method without a matching catch block being found, the entire program is terminated and a textual description of the exception is written to the standard output stream. The statements within the finally block are always executed after the try and catch blocks, whether or not an exception was thrown. Such blocks are useful for providing clean-up code. Either catch or finally block, or both must follow the try block.

Object-oriented programming (OOP) C# has direct support for object-oriented programming. Objects An object is created with the type as a template and is called an instance of that particular type. In C# objects are either references or values. No further syntactical distinction is made between those in code. object class All types, even value types in their boxed form, implicitly inherit from the System.Object class which is the ultimate base class of all objects. The class contains the most common methods shared by all objects. Some of these are virtual and can be overridden. Classes inherit System.Object either directly or indirectly through another base class. Members Some of the members of the Object class: Equals - Supports comparisons between objects. Finalize - Performs cleanup operations before an object is automatically reclaimed. (Default destructor) GetHashCode - Gets the number corresponding to the value of the object to support the use of a hash table. GetType - Gets the Type of the current instance. ToString - Creates a human-readable text string that describes an instance of the class. Usually it returns the name of the type. Classes Classes are fundamentals of an object-oriented language such as C#. They serve as a template for objects. They contain members that store and manipulate data in a real-life-like way.

See also Class (computer science) Structure (computer science) Differences between classes and structs Although classes and structures are similar in both the way they are declared and how they are used, there are some significant differences. Classes are reference types and structs value types. A structure is allocated on the stack when it is declared and the variable is bound to its address. It directly contains the value. Classes are different because the memory is allocated as objects on the heap. Variables are rather managed pointers on the stack which point to the objects. They are references. Structures require some more than classes. For example, you need to explicitly create a default constructor which takes no arguments to initialize the struct and its members. The compiler will create a default one for classes. All fields and properties of a struct must have been initialized before an instance is created. Structs do not have finalizers and cannot inherit from another class like classes do. However, they inherit from System.ValueType, that inherits from System.Object. Structs are more suitable for smaller constructs of data. This is a short summary of the differences:
Default constructor Finalizer Member initialization Inheritance

Classes

not required (auto generated)

yes

not required

yes (if base class is not sealed)

Structs

required (not auto generated)

no

required

not supported

Declaration A class is declared like this: class Foo { // Member declarations } Partial class This is a feature of C# 2.0. A partial class is a class declaration whose code is divided into separate files. The different parts of a partial class must be marked with keyword partial. // File1.cs partial class Foo { ... } // File2.cs partial class Foo { ... }

Initialization Before you can use the members of the class you need to initialize the variable with a reference to an object. To create it you call the appropriate constructor using the new keyword. It has the same name as the class. Foo foo = new Foo(); For structs it is optional to explicitly call a constructor because the default one is called automatically. You just need to declare it and it gets initialized with standard values.

Object initializers This is a feature of C# 3.0. Provides a more convenient way of initializing public fields and properties of an object. Constructor calls are optional when there is a default constructor. Person person = new Person { Name = "John Doe", Age = 39 }; // Equal to Person person = new Person(); person.Name = "John Doe"; person.Age = 39;

Collection initializers This is a feature of C# 3.0. Collection initializers give an array-like syntax for initializing collections. The compiler will simply generate calls to the Add-method. This works for classes that implement the interface ICollection. List<int> list = new List<int> {2, 5, 6, 6 }; // Equal to List<int> list = new List<int>(); list.Add(2); list.Add(5); list.Add(6); list.Add(6); Accessing members Members of an instance and static members of a class are accessed using the . operator. Accessing an instance member Instance members can be accessed through the name of a variable. string foo = "Hello"; string fooUpper = foo.ToUpper(); Accessing a static class member Static members are accessed by using the name of the class or other type. int r = String.Compare(foo, fooUpper); Accessing a member through a pointer In unsafe code, members of a value (struct type) referenced by a pointer are accessed with the -> operator just like in C and C++. POINT p; p.X = 2; p.Y = 6; POINT* ptr = &p; ptr->Y = 4;

Type-parameters Type-parameters are names used in place of concrete types when defining a new generic. They may be associated with classes or methods by placing the type parameter in angle brackets < >. When instantiating (or calling) a generic, you can then substitute a concrete type for the type-parameter you gave in its declaration. Type parameters may be constrained by use of the where keyword and a constraint specification, any of the six comma separated constraints may be used:

Constraint where T : struct

Explanation type parameter must be a value type type parameter must be a reference type type parameter must have a constructor with no parameters (must appear last) type parameter must inherit from <base_class> type parameter must be, or must implement this interface naked type parameter constraint

where T : class

where T : new()

where T : <base_class> where T : <interface> where T : U

Covariance and contravariance This is a feature of C# 4.0 and .NET Framework 4.0. Generic interfaces and delegates can have their type parameters marked as covariant or contravariant, using keywords out and in, respectively. These declarations are then respected for type conversions, both implicit and explicit, and both compile-time and run-time. For example, the existing interface IEnumerable<T> has been redefined as follows: interface IEnumerable<out T> { IEnumerator<T> GetEnumerator(); } Therefore, any class that implements IEnumerable<Derived> for some class Derived is also considered to be compatible with IEnumerable<Base> for all classes and interfaces Base that Derived extends, directly, or indirectly. In practice, it makes it possible to write code such as: void PrintAll(IEnumerable<object> objects) { foreach (object o in objects) { System.Console.WriteLine(o); } } IEnumerable<string> strings = new List<string>(); PrintAll(strings); // IEnumerable<string> is implicitly converted to IEnumerable<object> For contravariance, the existing interface IComparer<T> has been redefined as follows: public interface IComparer<in T> { int Compare(T x, T y); } Therefore, any class that implements IComparer<Base> for some class Base is also considered to be compatible with IComparer<Derived> for all classes and interfaces Derived that are extended from Base. It makes it possible to write code such as: IComparer<object> objectComparer = GetComparer(); IComparer<string> stringComparer = objectComparer;

Enumerators An enumerator is an iterator. Enumerators are typically obtained by calling the GetEnumerator() method of an object implementing the IEnumerable interface. Container classes typically implement this interface. However, the foreach statement in C# can operate on any object providing such a method, even if it doesn't implement IEnumerable. This interface was expanded into generic version in .NET 2.0. The following shows a simple use of iterators in C# 2.0: // explicit version IEnumerator<MyType> iter = list.GetEnumerator(); while (iter.MoveNext()) Console.WriteLine(iter.Current); // implicit version foreach (MyType value in list) Console.WriteLine(value);

Case sensitivity C# is case-sensitive, including its variable and method names. The variables myInteger and MyInteger below are distinct because C# is case-sensitive: int myInteger = 3; int MyInteger = 5; The following code will generate a compiler error (unless a custom class or variable named console has a method named writeline()): // Compiler error! console.writeline("Hello"); The following corrected code compiles as expected because it uses the correct case: Console.WriteLine("Hello");

Comments Comments allow inline documentation of source code. The C# compiler ignores comments. Three styles of comments are allowed in C#: Single-line comments The "//" character sequence marks the following text as a single-line comment. Single-line comments, as one would expect, end at the first end-of-line following the "//" comment marker. Multiple-line comments Comments can span multiple lines by using the multiple-line comment style. Such comments start with "/*" and end with "*/". The text between those multi-line comment markers is the comment. //This style of a comment is restricted to one line. /* This is another style of a comment. It allows multiple lines. */ XML Documentation-line comments This comment is used to generate XML documentation. Each line of the comment begins with "///". /// <summary> documentation here </summary> This is the most recommended type. Avoid using butterfly style comments. For example: //************************** // Butterfly style documentation comments like this are not recommended.

Inheritance polymorphism A value can be implicitly converted to any class from which it inherits or interface that it implements. To convert a base class to a class that inherits from it, the conversion must be explicit in order for the conversion statement to compile. Similarly, to convert an interface instance to a class that implements it, the conversion must be explicit in order for the conversion statement to compile. In either case, the runtime environment throws a conversion exception if the value to convert is not an instance of the target type or any of its derived types. Scope and extent The scope and extent of variables is based on their declaration. The scope of parameters and local variables corresponds to the declaring method or statement block, while the scope of fields is associated with the instance or class and is potentially further restricted by the field's access modifiers. The extent of variables is determined by the runtime environment using implicit reference counting and a complex garbage collection algorithm.

Custom types The predefined types can be aggregated and extended into custom types. Custom value types are declared with the struct or enum keyword. Likewise, custom reference types are declared with the class keyword. Arrays Although the number of dimensions is included in array declarations, the size of each dimension is not: string[] s ; Assignments to an array variable (prior to the variable's usage), however, specify the size of each dimension:

s = new string[5] ; As with other variable types, the declaration and the initialization can be combined: string[] s = new string[5] ; It is also important to note that like in Java, arrays are passed by reference, and not passed by value. For example, the following code snippet successfully swaps two elements in an integer array: static void swap (int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } Conversion Values of a given type may or may not be explicitly or implicitly convertible to other types depending on predefined conversion rules, inheritance structure, and explicit cast definitions. Predefined conversions Many predefined value types have predefined conversions to other predefined value types. If the type conversion is guaranteed not to lose information, the conversion can be implicit (i.e. an explicit cast is not required).

C# operators and their precedence closely resemble the operators in other languages of the C family.C Similar to C++, classes can overload most operators, defining or redefining the behavior of the operators in contexts where the first argument of that operator is an instance of that class, but doing so is often discouraged for clarity. Following are the built-in behaviors of C# operators.

Arithmetic The following arithmetic operators operate on numeric operands (arguments a and b in the "sample usage" below).Sample usage Read Explanation a+b a plus b The binary operator + returns the sum of its arguments. a-b a minus b The binary operator - returns the difference between its arguments. a*b a times b The binary operator * returns the multiplicative product of its arguments. a/b a divided by b The binary operator / returns the quotient of its arguments. If both of its operators are integers, it obtains that quotient using integer division (i.e. it drops any resulting remainder). a%b a mod b The binary operator % operates only on integer arguments. It returns the remainder of integer division of those arguments. (See modular arithmetic.) a++ a plus plus The unary operator ++ operates only on arguments that have an l-value. When placed after its argument, it increments that argument by 1 and returns the value of that argument before it was incremented. ++a plus plus a The unary operator ++ operates only on arguments that have an l-value. When placed before its argument, it increments that argument by 1 and returns the resulting value. a-a minus minus The unary operator -- operates only on arguments that have an l-value. When placed after its argument, it decrements that argument by 1 and returns the value of Operators that argument before it was decremented. --a minus minus a The unary operator -- operates only on arguments that have an l-value. When placed before its argument, it decrements that argument by 1 and returns the resulting value. Logical The following logical operators operate on boolean or integral operands, as noted.Sample usage Read Explanation a&b a bitwise and b The binary operator & evaluates both of its operands and returns the logical conjunction ("AND") of their results. If the operands are integral, the logical conjunction is performed bitwise.

a && b a and b The binary operator && operates on boolean operands only. It evaluates its first operand. If the result is false, it returns false. Otherwise, it evaluates and returns the results of the second operand. Note that if evaluating the second operand would hypothetically have no side effects, the results are identical to the logical conjunction performed by the & operator. a|b a bitwise or b The binary operator | evaluates both of its operands and returns the logical disjunction ("OR") of their results. If the operands are integral, the logical disjunction is performed bitwise. a || b a or b The binary operator || operates on boolean operands only. It evaluates the first operand. If the result is true, it returns true. Otherwise, it evaluates and returns the results of the second operand. Note that if evaluating the second operand would hypothetically have no side effects, the results are identical to the logical disjunction performed by the | operator. Operators than or equal to b true if a is less than or equal to b, false otherwise. a >= b a is greater than or equal to b The operator >= operates on integral types. It returns true if a is greater than or equ a^b a x-or b The binary operator ^ returns the exclusive or ("XOR") of their results. If the operands are integral, the exclusive or is performed bitwise. !a not a The unary operator ! operates on a boolean operand only. It evaluates its operand and returns the negation ("NOT") of the result. That is, it returns true if a evaluates to false and it returns false if a evaluates to true. ~a bitwise The unary operator ~ operates on integral operands only. It

not a evaluates its operand and returns the bitwise negation of the result. That is, ~a returns a value where each bit is the negation of the corresponding bit in the result of evaluating a.

Bitwise shiftingSample usage Read Explanation a << b a left shift b The binary operator << evaluates its operands and returns the resulting first argument left-shifted by the number of bits specified by the second argument. It discards high-order bits that shift beyond the size of its first argument and sets new low-order bits to zero. a >> b a right shift b The binary operator >> evaluates its operands and returns the resulting first argument right-shifted by the number of bits specified by the second argument. It discards low-order bits that are shifted beyond the size of its first argument and sets new highorder bits to the sign bit of the first argument, or to zero if the first argument is unsigned. Relational The binary relational operators ==, !=, <, >, <=, and >= are used for relational operations and for type comparisons.Sample usage Read Explanation a == b a is equal to b For arguments of value type, the operator == returns true if its operands have the same value, false otherwise. For the string type, it returns true if the strings' character sequences match. For other reference types (types derived from System.Object), however, a == b returns true only if a and b reference the same object. a != b a is not equal to b The operator != returns the logical negation of the operator ==. Thus, it returns true if a is not equal to b, and false if they are equal. a<b a is less than b The operator < operates on integral types. It returns true if a is less than b, false otherwise. a>b a is greater than b The operator > operates on integral types. It returns true if a is greater than b, false otherwise. a <= b a is less The operator <= operates on integral types. It returns

Assignment The assignment operators are binary. The most basic is the operator =. Not surprisingly, it assigns the value of its second argument to its first argument. (More technically, the operator = requires for its first (left) argument an expression to which a value can be assigned (an l-value) and for its second (right) argument an expression which can be evaluated (an r-value). That requirement of an assignable expression to its left and a bound expression to its right is the origin of the terms l-value and r-value.) The first argument of the assignment operator (=) is typically a variable. When that argument has a value type, the assignment operation changes the argument's underlying value. When the first argument is a reference type, the assignment operation changes the reference, so the first argument typically just refers to a different object but the object that it originally referenced does not change (except that it may no longer be referenced and may thus be a candidate for garbage collection).Sample usage Read Explanation a=b a equals (or set to) b The operator = evaluates its second argument and then assigns the results to (the l-value indicated by) its first argument. a = b = c b set to c, and then a set to b Equivalent to a = (b = c). When there are consecutive assignments, the right-most assignment is evaluated first, proceeding from right to left. In this example, both variables a and b have the value of c. Short-hand Assignment The short-hand assignment operators shortens the common assignment operation of a = a operator b into a operator= b, resulting in less typing and neater syntax.Sample usage Read Explanation a += b a -= b a *= b a plus equals (or increment by) b Equivalent to a = a + b. a minus equals (or decrement by) b Equivalent to a = a - b. a multiply equals (or multiplied by) b Equivalent to a = a * b.

a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b

a divide equals (or divided by) b Equivalent to a = a / b. a mod equals b Equivalent to a = a % b. a and equals b Equivalent to a = a & b. a or equals b Equivalent to a = a | b. a xor equals b Equivalent to a = a ^ b. a left-shift equals b Equivalent to a = a << b. a right-shift equals b Equivalent to a = a >> b.

Type informationExpression Explanation x is T returns true if the variable x of base class type stores an object of derived class type T, or, if x is of type T. Else returns false. x as T returns (T)x (x casted to T) if the variable x of base class type stores an object of derived class type T, or, if x is of type T. Else returns null. Equivalent to x is T ? (T)x : null sizeof(x) returns the size of the value type x. Remarks: The sizeof operator can be applied only to value types, not reference types. The sizeof operator can only be used in the unsafe mode. he type. T must be the name of the type, and not a variable. Use the GetType method to retrieve run-time type information
Pointer manipulationExpression typeof(T) returns a System.Type object describing tExplanation To be done *, ->, [], & Overflow exception controlExpression Explanation checked(a) uses overflow checking on value a unchecked(a) avoids overflow checking on value a

C# classes support information hiding by encapsulating functionality in properties and methods and by enabling several types of polymorphism, including subtyping polymorphism via inheritance and parametric polymorphism via generics. Several types of C# classes can be defined, including instance classes (standard classes that can be instantiated), static classes, and structures. Classes are defined using the keyword "class" followed by an identifier to name the class. Instances of the class can then be created with the "new" keyword followed by the name of the class. The code below defines a class called Employee with properties Name and Age and with empty methods GetPayCheck() and Work(). It also defines a Sample class that instantiates and uses the Employee class: public class Employee { private string _name; private int _age; public string Name { set { _name = value; } get { return _name; } } public int Age { set { _age = value; } get { return _age; } } public void GetPayCheck() { }

public void Work() { } } public class Sample { public static void Main() { Employee Marissa = new Employee(); Marissa.Work(); Marissa.GetPayCheck(); } }

Methods C# methods are class members containing code. They may have a return value and a list of parameters, as well as a generic type declaration. Like fields, methods can be static (associated with and accessed through the class) or instance (associated with and accessed through an object instance of the class). Constructors A class's constructors control its initialization. A constructor's code executes to initialize an instance of the class when a program requests a new object of the class's type. Constructors often set properties of their classes, but they are not restricted to doing so. Like other methods, a constructor can have parameters. To create an object using a constructor with parameters, the new command accepts parameters. The below code defines and then instantiates multiple objects of the Employee class, once using the constructor without parameters and once using the version with a parameter:

public class Employee { public Employee() { System.Console.WriteLine("Constructed without parameters"); } public Employee(string text) { System.Console.WriteLine(text); } } public class Sample { public static void Main() { System.Console.WriteLine("Start"); Employee Alfred = new Employee(); Employee Billy = new Employee("Parameter for construction"); System.Console.WriteLine("End"); } } Output: Start Constructed without parameters Parameter for construction

Finalizers The opposite of constructors, finalizers define final the behavior of an object C++ to free memory reserved by an object, they are less frequently used in C# due to the .NET Framework Garbage Collector. An object's finalizer, which takes no parameters, is called sometime after an object is no longer referenced, but the complexities of garbage collection make the specific timing of finalizers uncertain. public class Employee { public Employee(string text) { System.Console.WriteLine(text); } ~Employee() { System.Console.WriteLine("Finalized!"); } public static void Main() { Employee Marissa = new Employee("Constructed!"); Marissa = null; } } Output: Constructed! Finalized! Properties C# properties are class members that expose functionality of methods using the syntax of fields.

They simplify the syntax of calling traditional get and set methods (a.k.a. accessor methods). Like methods, they can be static or instance. Properties are defined in the following way: public class MyClass { private int integerField = 3; // Sets integerField with a default value of 3 public int IntegerField { get { return integerField; // get returns the field you specify when this property is assigned } set { integerField = value; // set assigns the value assigned to the property of the field you specify } } } The C# keyword value contains the value assigned to the property. After a property is defined it can be used like a variable. If you were to write some method and allow you to manipulate the data before it is read or written to the variable. using System; public class MyProgram { MyClass myClass = new MyClass; Console.WriteLine(myClass.IntegerField); // Writes 3 to the command line. myClass.IntegerField = 7; // Indirectly assigns 7 to the field myClass.integerField }

Using properties in this way provides a clean, easy to use mechanism for protecting data.

Indexers C# indexers are class members that define the behavior of the array access operation (e.g. list[0] to access the first element of list even when list is not an array). To create an indexer, use the this keyword as in the following example: public string this[string key] { get {return coll[_key];} set {coll[_key] = value;} } This code will create a string indexer that returns a string value. For example, if the class was EmployeeCollection, you could write code similar to the following: EmployeeCollection e = new EmployeeCollection();. . . string s = e["Jones"]; e["Smith"] = "xxx"; Structures Structures, or structs, are defined with the struct keyword followed by an identifier to name the structure. They are similar to classes, but have subtle differences. Structs are used as lightweight versions of classes that can help reduce memory management efforts in when working with small data structures. In most situations, however, using a standard class is a better choice. The principal difference between structs and classes is that instances of structs are values whereas instances of classes are references. Thus when you pass a struct to a function by value you get a copy of the object so changes to it are not reflected in the original because there are now two distinct objects but if you pass an instance of a class by value then there is only one instance. e outside it.

The Employee structure below declares a public and a private field. Access to the private field is granted through the public property "Name": struct Employee { private string name; public int age; public string Name { set { name = value; } get { return name; } } } Static classes Static classes are commonly used to implement a Singleton Pattern. All of the methods, properties, and fields of a static class are also static (like the WriteLine() method of the System.Console class) and can thus be used without instantiating the static class: public static class Writer { public static void Write() { System.Console.WriteLine("Text"); } } public class Sample {

public static void Main() { Writer.Write(); } } Encapsulation is depriving of the user of a class information he does not need, and preventing him from manipulating objects in ways not intended by the designer.E A class element having public protection level is accessible to all code anywhere in the program. These methods and properties represent the operations allowed on the class to outside users. Methods, data members (and other elements) with private protection level represent the internal state of the class (for variables), and operations which are not allowed to outside users. For example: public class Frog { public void JumpLow() { Jump(1); } public void JumpHigh() { Jump(10); } private void Jump(int height) { _height += height;} private int _height = 0; } In this example, the public method the Frog class exposes are JumpLow and JumpHigh. Internally, they are implemented using the private Jump function that can jump to any height. This operation is not visible to an outside user, so he cannot make the frog jump 100 meters, only 10 or 1. The Jump private method is implemented by changing the value of a private data member _height, which is also not visible to an outside user. Some private data members are made visible by properties. Protection Levels

Private Private members are only accessible within the class itself. A method in another class, even a class derived from the class with private members cannot access the members. Protected Protected members can be accessed by the class itself and by any class derived from that class. Public Public members can be accessed by any method in any class. Internal Internal members are accessible only in the same assembly and invisibl Command line arguments Command line arguments are values that are passed to a console program before execution. For example, the Windows command prompt includes a copy command that takes two command line arguments. The first argument is the original file and the second is the location or name for the new copy. Custom console applications can have arguments as well. using System; public class ExampleClass { public static void Main(string[] args) { Console.WriteLine("First Name: " + args[0]); Console.WriteLine("Last Name: " + args[1]); Console.Read();

} } If the program above code is compiled to a program called username.exe, it can be executed from the command line using two arguments, e.g. "Bill" and "Gates": C:\>username.exe Bill Gates Notice how the Main() method above has a string array parameter. The program assumes that there will be two arguments. That assumption makes the program unsafe. If it is run without the expected number of command line arguments, it will crash when it attempts to access the missing argument. To make the program more robust, we make we can check to see if the user entered all the required arguments. using System; public class Test { public static void Main(string[] args) { if(args.Length >= 1) Console.WriteLine(args[0]); if(args.Length >= 2) Console.WriteLine(args[1]); } } Try running the program with only entering your first name or no name at all. The string.Length property returns the total number of arguments. If no arguments are given, it will return zero.

Inheritance is the ability to create a class from another class, and extending the functionality and state of the derived class.I Inheritance in C# also allows derived classes to overload methods from their parent class. Inheritance(by Mine) Subtyping Inheritance The code sample below shows two classes, Employee and Executive. Employee has the following methods, GetPayCheck and Work. We want the Executive class to have the same methods, but differently implemented and one extra method, AdministerEmployee. Below is the creation of the first class to be derived from, Employee. public class Employee { // we declare one method virtual so that the Executive class can // override it. public virtual void GetPayCheck() { //get paycheck logic here. } //Employee's and Executives both work, so no virtual here needed. public void Work() { //do work logic here. } }

Executive exec = new Executive; emp.Work(); exec.Work(); emp.GetPayCheck(); exec.GetPayCheck(); exec.AdministerEmployee(); } Inheritance keywords How C# inherits from another class syntacticaly is using the ":" character. Example. public class Executive : Employee To indicate a method that can be overridden, you mark the method with virtual. public virtual void Write(string text) { System.Console.WriteLine("Text:{0}", text); } To override a method use the override keyword public override void Write(string text) { System.Console.WriteLine(text); }

Some Important Points for Interface Access specifiers (i.e. private, internal, etc) cannot be provided for interface members. In Interface, all members are public by default. A class implementing an interface must define all the members declared by the interface as public. The implementing class has the option of making an implemented method virtual if it is expected to be overridden in a a child class. In addition to methods and properties, interfaces can declare events and indexers as well.

n interface in C# is type definition similar to a class except that it purely represents a contract between an object and a user of the object. An interface cannot be directly instantiated as an object. No data members can be defined in an interface. Methods and properties can only be declared, not defined. For example, the following defines a simple interface:A interface IShape { void Draw(); double X { get; set; } double Y { get; set; } } A convention used in the .NET Framework (and likewise by many C# programmers) is to place an "I" at the beginning of an interface name to distinguish it from a class name. Another common interface naming convention is used when an interface declares only one key method, such Draw() in the above example. The interface name is then formed by adding the suffix "able" to the method name. So, in the above example, the interface name would be IDrawable. This convention is also used throughout the .NET Framework. Implementing an interface is simply done by inheriting off the interface and then defining all the methods and properties declared by the interface. For example: class Square : IShape { private double mX, mY; public void Draw() { ... } public double X { set { mX = value; } get { return mX; } }

elegates are a construct for abstracting and creating objects that reference methods and can be used to call those methods. Delegates form the basis of event handling in C#. A delegate declaration specifies a particular method signature. References to one or more methods can be added to a delegate instance. The delegate instance can then be "called" which effectively calls all the methods that have been added to the delegate instance. A simple example:D delegate void Procedure(); class DelegateDemo { static void Method1() { Console.WriteLine("Method 1"); } static void Method2() { Console.WriteLine("Method 2"); } void Method3() { Console.WriteLine("Method 3"); } elegates are a construct for abstracting and creating objects that reference methods and can be used to call those methods. Delegates form the basis of event handling in C#. A delegate declaration specifies a particular method signature. References to one or more methods can be added to a delegate instance. The delegate instance can then be "called" which effectively calls all the methods that have been added to the delegate instance. A simple example:D

delegate void Procedure(); class DelegateDemo { static void Method1() { Console.WriteLine("Method 1"); } static void Method2() { Console.WriteLine("Method 2"); } void Method3() { Console.WriteLine("Method 3"); } Object references can be declared using an interface type. For example, using the previous examples: class MyClass { static void Main() { IShape shape = new Square(); shape.Draw(); } }

Intefaces can inherit off of any number of other interfaces but cannot inherit from classes. For example: interface IRotateable { void Rotate(double theta); } interface IDrawable : IRotateable { void Draw(); } static void Main() { Procedure someProcs = null; someProcs += new Procedure(DelegateDemo.Method1); someProcs += new Procedure(DelegateDemo.Method2); DelegateDemo demo = new DelegateDemo(); someProcs += new Procedure(demo.Method3); someProcs(); } } In this example, the delegate is declared by the line delegate void Procedure(); This statement is a complete abstraction. It does not result in executable code that does any work. It merely declares a delegate type called Procedure which takes no arguments and returns nothing. Next, in the Main() method, the statement Procedure someProcs = null; instantiates a delegate. Something concrete has now been created. The assignment of someProcs to null means that it is not initially referencing any methods. The statements someProcs += new Procedure(DelegateDemo.Method1); and someProcs += new Procedure(DelegateDemo.Method2); add two static methods to the delegate instance. (Note: the class name could have been left off of DelegateDemo.Method1 and DelegateDemo.Method2 because

the statement is occurring in the DelegateDemo class.) The statement someProcs += new Procedure(demo.Method3); adds a non-static method to the delegate instance When the delegate instance is called, Method3() is called on the object that was supplied when the method was added to the delegate instance. Finally, the statement someProcs(); calls the delegate instance. All the methods that were added to the delegate instance are now called in the order that they were added. Methods that have been added to a delegate instance can be removed with the -= operator: someProcess -= new Procedure(DelegateDemo.Method1); In C# 2.0, adding or removing a method reference to a delegate instance can be shortened as follows: someProcess += DelegateDemo.Method1; someProcess -= DelegateDemo.Method1; Invoking a delegate instance that presently contains no method references results in a NullReferenceException. Note that if a delegate declaration specifies a return type and multiple methods are added to a delegate instance, then an invocation of the delegate instance returns the return value of the last method referenced. The return values of the other methods cannot be retrieved (unless explicitly stored somewhere in addition to being returned).

Events An event is a special kind of delegate that facilitates event-driven programming. Events are class members which cannot be called outside of the class regardless of its access specifier. So, for example, an event declared to be public would allow other classes the use of += and -= on the event, but firing the event (i.e. invoking the delegate) is only allowed in the class containing the event. A

simple example: delegate void ButtonClickedHandler(); class Button { public event ButtonClickedHandler ButtonClicked; public void SimulateClick() { if (ButtonClicked != null) { ButtonClicked(); } } ... } methods to the event delegate: Button b = new Button(); b.ButtonClicked += MyHandler; Even though the event is declared public, it cannot be directly fired anywhere except in the class containing the event. Events are used extensively in GUI programming and in the System.Windows.Forms namespace An abstract class is a class that is never intended to be instantiated directly, but only to serve as a base to other classes. An abstract class should contain at least one abstract method which derived concrete classes will implement. A class should be made abstract when there are some aspects of

the implementation which must be deferred to a more specific subclass.A For example, an Employee can be an abstract class if there are concrete classes that represent more specific types of Employee (e.g. SalariedEmployee, TemporaryEmployee, etc.). Although it is not possible to instantiate the Employee class directly, a program may create instances of SalariedEmployee and TemporaryEmployee, both of which inherit the behavior defined in the Employee class.

As the name indicates, partial class definitions can be split up across multiple physical files. To the compiler, this does not make a difference as all the fragments of the partial class are grouped and the compiler treats it as a single class. One common usage of partial classes is the separation of automatically generated code from programmer written code.A Below is the example of a partial class. Listing 1: Entire class definition in one file (file1.cs) public class Node { public bool Delete() { } public bool Create() { } } Listing 2: Class split across multiple files (file1.cs) public partial class Node {

public bool Delete() { } } (file2.cs) public partial class Node { public bool Create() { } } Generics is essentially the ability to have type parameters on your type. They are also called parameterized types or parametric polymorphism. The classic example is a List collection class. A List is a convenient growable array. It has a sort method, you can index into it, and so on.G Generic Interfaces MSDN2 Entry for Generic Interfaces Generic Classes There are cases, when you need to create some class to manage objects of some type, without modyfing them. Without Generics, usual approach (highly simplified) to make such class would be like this: public class SomeObjectContainer { private object obj; public SomeObjectContainer(object obj) { this.obj = obj;

} public object getObject() { return this.obj; } } And the usage of it would be: class Program { static void Main(string[] args) { SomeObjectContainer container = new SomeObjectContainer(25); SomeObjectContainer container2 = new SomeObjectContainer(5); Console.WriteLine((int)container.getObject() + (int)container2.getObject()); Console.ReadKey(); // wait for user to press any key, so we could see results } } Notice, that we have to cast back to original data type we have chosen (in this case - int) every time we want to get object from such container. In such small program like this, everything is clear. But in more complicated case with more containers in different parts of program, we would have to take care that container, supposed to have int type in it, would not have a string or any other

data type. If that happens, InvalidCastException is thrown. Additionally, if the original data type we have chosen is a struct type, such as int, we will incur a performance penalty every time we access the elements of the collection, due to the Autoboxing feature of C#.

However, we could surround every unsafe area with try - catch block, or we could create separate "container" for every data type we need, just to avoid casting. While both ways could work (and worked for many years), it is unnecessary now, because Generics offers much more elegant solution. To make our "container" class to support any object and avoid casting, we replace every previous object type with some new name, in this case - T, and add <T> mark near class name to indicate that this "T" type is Generic / any type. Note: You can choose any name and use more than one generic type for class, i.e <genKey, genVal> public class GenericObjectContainer<T> { private T obj; public GenericObjectContainer(T obj) { this.obj = obj; } public T getObject() { return this.obj; } } Not a big difference, which results in simple and safe usage: class Program { static void Main(string[] args) {

GenericObjectContainer<int> container = new GenericObjectContainer<int>(25); GenericObjectContainer<int> container2 = new GenericObjectContainer<int>(5); Console.WriteLine(container.getObject() + container2.getObject()); Console.ReadKey(); // wait for user to press any key, so we could see results } } Generics ensures, that you specify type for "container" only when creating it, and after that you will be able to use only the type you specified. But now you can create containers for different object types, and avoid previously mentioned problems. In addition, this avoids the Autoboxing for struct types. While this example is far from practical, it does illustrate some situations where generics are useful: You need to keep objects of single type in some class You don't need to modify objects You need to manipulate objects in some way You wish to store a "value type" (such as int, short, string, or any custom struct) in a collection class without incurring the performance penalty of Autoboxing every time you manipulate the stored elements. Different programming languages deal with issues of object lifetime in different ways and this must be accounted for when writing programs because some objects must be disposed of at specific moments while others can be allowed to exist until the program terminates or a garbage collector disposes of it.D If you are coming to C# from Visual Basic Classic you will have seen code like this: Public Function Read(ByRef FileName) As String Dim oFSO As FileSystemObject

Set oFSO = New FileSystemObject Dim oFile As TextStream Set oFile = oFSO.OpenTextFile(FileName, ForReading, False) Read = oFile.ReadLine End Function Note that neither oFSO nor oFile are explicitly disposed of. In Visual Basic Classic this is not necessary because both objects are declared locally. This means that the reference count goes to zero as soon as the function ends which results in calls to the Terminate event handlers of both objects. Those event handlers close the file and release the associated resources. In C# this doesn't happen because the objects are not reference counted. The finalizers will not be called until the garbage collector decides to dispose of the objects. If the program uses very little memory this could be a long time. This causes a problem because the file is held open which might prevent other processes from accessing it. In many languages the solution is to explicitly close the file and dispose of the objects and many C# programmers do just that. However, there is a better way: use the using statement: public read(string fileName)

{ using (TextReader textReader = new StreamReader(filename)) { return textReader.ReadLine(); } }

Behind the scenes the compiler turns the using statement into try..finally and produces this intermediate language (IL) code: .method public hidebysig static string Read(string FileName) cil managed { // Code size 39 (0x27) .maxstack 5 .locals init (class [mscorlib]System.IO.TextReader V_0, string V_1) IL_0000: ldarg.0 IL_0001: newobj instance void [mscorlib]System.IO.StreamReader::.ctor(string) IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: callvirt instance string [mscorlib]System.IO.TextReader::ReadLine() IL_000d: stloc.1 IL_000e: leave IL_0025 IL_0013: leave IL_0025 } // end .try finally { IL_0018: ldloc.0 IL_0019: brfalse IL_0024 IL_001e: ldloc.0 IL_001f: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_0024: endfinally

} // end handler IL_0025: ldloc.1 IL_0026: ret } // end of method Using::Read Notice that the body of the Read function has been split into three parts: initialisation, try, and finally. The finally block includes code that was never explicitly specified in the original C# source code, namely a call to the destructor of the Streamreader instance. See Understanding the 'using' statement in C# By TiNgZ aBrAhAm. Resource Acquisition Is Initialisation The application of the using statement in the introduction is an example of an idiom called Resource Acquisition Is Initialisation (RAII). RAII is a natural technique in languages like Visual Basic Classic and C++ that have deterministic finalization but usually requires extra work to include in programs written in garbage collected languages like C# and VB.NET. The using statement makes it just as easy. Of course you could write the try..finally code out explicitly and in some cases that will still be necessary. For a thorough discussion of the RAII technique see HackCraft: The RAII Programming Idiom. Wikipedia has a brief note on the subject as well: Resource Acquisition Is Initialization. Work in progress: add C# versions showing incorrect and correct methods with and without using. Add notes on RAII, memoization and cacheing (see OOP wikibook) STANDARD Microsoft, Anders Hejlsberg as Chief Engineer, created C# as part of their .NET initiative and subsequently opened its specification via the ECMA. Thus, the language is open to implementation by other parties. Other implementations include Mono and DotGNU. C# and other .NET languages rely on an implementation of the virtual machine specified in the Common Language Infrastructure, like Microsoft's Common Language Runtime (CLR). That virtual machine manages memory, handles object references, and performs Just-In-Time (JIT) compiling of Common Intermediate Language code. The virtual machine makes C# programs safer

than those that must manage their own memory and is one of the reasons .NET language code is referred to as managed code. More like Java than C and C++, C# discourages explicit use of pointers, which could otherwise allow software bugs to corrupt system memory and force the operating system to halt the program forcibly with nondescript error messages. Dialects Spec# Main article: Spec Sharp Spec# is a dialect of C# that is developed in parallel with the standard implementation from Microsoft. It extends C# with specification language features and is a possible future feature to the C# language. It also adds syntax for the code contracts API that was introduced in .NET Framework 4.0. Spec# is being developed by Microsoft Research. This sample shows two of the basic structures that are used when adding contracts to your code. static void Main(string![] args) requires args.Length > 0 { foreach(string arg in args) { } } ! is used to make a reference type non-nullable, e.g. you cannot set the value to null. This in contrast of nullable types which allow value types to be set as null. requires indicates a condition that must be followed in the code. In this case the length of args is not allowed to be zero or less. Non-nullable types Spec# extends C# with non-nullable types that simply checks so the variables of nullable types that has been set as non-nullable are not null. If is null then an exception will be thrown. string! input In use: public Test(string! input) { ... }

Preconditions Preconditions are checked before a method is executed. public Test(int i) requires i > 0; { this.i = i; } Postconditions Postconditions are conditions that are ensured to be correct when a method has been executed. public void Increment() ensures i > 0; { i++; } Checked exceptions Spec# adds checked exceptions like those in Java. Attributes Attributes are entities of data that is stored as metadata in the compiled assembly. An attribute can be added to types and members like properties and methods. Attributes can be used for better maintenance of preprocessor directives. [CompilerGenerated]public class $AnonymousType$120{ [CompilerGenerated] public string Name { get; set; }} The .NET Framework comes with predefined attributes that can be used. Some of them serve an important role at runtime while some are just for syntactic decoration in code like CompilerGenerated. It does only mark that it is a compiler-generated element. Programmer-defined attributes can also be created.

An attribute is essentially a class which inherits from the System.Attribute class. By convention, attribute classes end with "Attribute" in their name. This will not be required when using it. public class EdibleAttribute : Attribute{ public EdibleAttribute() : base() { } public EdibleAttribute(bool isNotPoisonous) { this.IsPoisonous = !isNotPoisonous; } public bool IsPoisonous { get; set; }} Showing the attribute in use using the optional constructor parameters. [Edible(true)]public class Peach : Fruit{ // Members if any}

Thread synchronization C# provides the lock statement, which is yet another example of beneficial syntactic sugar. It works by marking a block of code as a critical section by mutual exclusion of access to a provided object. Like the using statement, it works by the compiler generating a try ... finally block in its place. private static StreamWriter _writer; public void ConcurrentMethod(){ lock (_writer) { _writer.WriteLine("Line 1."); _writer.WriteLine("Followed by line 2."); }}
Miscellaneous Closure Blocks C# implements closure blocks by means of the using statement. The using statement accepts an expression which results in an object implementing IDisposable, and the compiler generates code that guarantees the object's disposal when the scope of the using-statement is exited. The using statement is syntactic sugar. It makes the code more readable than the equivalent try ... finally block. public void Foo(){ using (var bar = File.Open("Foo.txt")) { // do some work throw new Exception(); // bar will still get properly disposed. }} Differences between classes and structs Although classes and structures are similar in both the way they are declared and how they are used, there are some significant differences. Classes are reference types and structs value types. A structure is allocated on the stack when it is declared and the variable is bound to its address. It directly contains the Member Finalizer value. Classes are differentDefault constructormemory is allocated as objects onInheritance Variables are rather because the the heap. initialization managed pointers on the stack which point to the objects. They are references. not required classes. yes (if base create Structures require some more than(auto yes For example, you need to explicitlyclass is a default Classes not required generated) not sealed) constructor which takes no arguments to initialize the struct and its members. The compiler will create a default one for classes. Allrequired (not auto fields and properties of a struct must have been initialized before an instance Structs no required not supported generated) is created. Structs do not have finalizers and cannot inherit from another class like classes do. However, they inherit from System.ValueType, that inherits from System.Object. Structs are more suitable for

smaller constructs of data. This is a short summary of the differences: Declaration A class is declared like this: class Foo{ // Member declarations} Partial class This is a feature of C# 2.0. A partial class is a class declaration whose code is divided into separate files. The different parts of a partial class must be marked with keyword partial. // File1.cspartial class Foo{ ...} // File2.cspartial class Foo{ ...} Initialization Before you can use the members of the class you need to initialize the variable with a reference to an object. To create it you call the appropriate constructor using the new keyword. It has the same name as the class. Foo foo = new Foo(); For structs it is optional to explicitly call a constructor because the default one is called automatically. You just need to declare it and it gets initialized with standard values.

You might also like