charina power p

Upload: kath-lapuz

Post on 05-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 ChaRina Power p . .

    1/77

    PROJECT IN SPL

    SUBMITTED BY :CHARLYN T. CASTRO

    RINA LYN P. ENCINA

    CT-23MS.AGUSTIN

  • 7/31/2019 ChaRina Power p . .

    2/77

    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, butchose 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 ofTurbo 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 programminglanguages (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 revolutionaryprogramming 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 ofreification to

    http://en.wikipedia.org/wiki/Base_Class_Libraryhttp://en.wikipedia.org/wiki/Managed_codehttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Anders_Hejlsberghttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Professional_Developers_Conferencehttp://en.wikipedia.org/wiki/ASP.NEThttp://en.wikipedia.org/wiki/Anders_Hejlsberghttp://en.wikipedia.org/wiki/Turbo_Pascalhttp://en.wikipedia.org/wiki/Embarcadero_Delphihttp://en.wikipedia.org/wiki/Visual_J++http://en.wikipedia.org/wiki/Visual_J++http://en.wikipedia.org/wiki/Wikipedia:Citation_neededhttp://en.wikipedia.org/wiki/C++http://en.wikipedia.org/wiki/Java_(programming_language)http://en.wikipedia.org/wiki/Embarcadero_Delphihttp://en.wikipedia.org/wiki/Smalltalkhttp://en.wikipedia.org/wiki/Common_Language_Runtimehttp://en.wikipedia.org/wiki/James_Goslinghttp://en.wikipedia.org/wiki/Java_(programming_language)http://en.wikipedia.org/wiki/Bill_Joyhttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Boxing_(Computer_Science)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Reification_(computer_science)http://en.wikipedia.org/wiki/Reification_(computer_science)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Boxing_(Computer_Science)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Bill_Joyhttp://en.wikipedia.org/wiki/Java_(programming_language)http://en.wikipedia.org/wiki/James_Goslinghttp://en.wikipedia.org/wiki/Common_Language_Runtimehttp://en.wikipedia.org/wiki/Smalltalkhttp://en.wikipedia.org/wiki/Embarcadero_Delphihttp://en.wikipedia.org/wiki/Java_(programming_language)http://en.wikipedia.org/wiki/C++http://en.wikipedia.org/wiki/Wikipedia:Citation_neededhttp://en.wikipedia.org/wiki/Visual_J++http://en.wikipedia.org/wiki/Visual_J++http://en.wikipedia.org/wiki/Embarcadero_Delphihttp://en.wikipedia.org/wiki/Turbo_Pascalhttp://en.wikipedia.org/wiki/Anders_Hejlsberghttp://en.wikipedia.org/wiki/ASP.NEThttp://en.wikipedia.org/wiki/Professional_Developers_Conferencehttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Anders_Hejlsberghttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Managed_codehttp://en.wikipedia.org/wiki/Base_Class_Library
  • 7/31/2019 ChaRina Power p . .

    3/77

    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 LINQextensions released with C# 3.0 and its supporting framework of lambdaexpressions, 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]

    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 ofC++, 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

    http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Type_erasurehttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/LINQhttp://en.wikipedia.org/wiki/Lambda_expressionshttp://en.wikipedia.org/wiki/Lambda_expressionshttp://en.wikipedia.org/wiki/Extension_methodhttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Closure_(computer_science)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Mascothttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C%E2%99%AF_(musical_note)http://en.wikipedia.org/wiki/Sharp_(music)http://en.wikipedia.org/wiki/Semitonehttp://en.wikipedia.org/wiki/Pitch_(music)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C++http://en.wikipedia.org/wiki/Sharp_(music)http://en.wikipedia.org/wiki/Number_signhttp://en.wikipedia.org/wiki/Number_signhttp://en.wikipedia.org/wiki/Sharp_(music)http://en.wikipedia.org/wiki/C++http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Pitch_(music)http://en.wikipedia.org/wiki/Semitonehttp://en.wikipedia.org/wiki/Sharp_(music)http://en.wikipedia.org/wiki/C%E2%99%AF_(musical_note)http://en.wikipedia.org/wiki/C%E2%99%AF_(musical_note)http://en.wikipedia.org/wiki/C%E2%99%AF_(musical_note)http://en.wikipedia.org/wiki/File:C_sharp_music.svghttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Mascothttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Closure_(computer_science)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Extension_methodhttp://en.wikipedia.org/wiki/Lambda_expressionshttp://en.wikipedia.org/wiki/Lambda_expressionshttp://en.wikipedia.org/wiki/LINQhttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Type_erasurehttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)
  • 7/31/2019 ChaRina Power p . .

    4/77

    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 ofEiffel for .NET was

    called Eiffel#,[11] a name since retired since the full Eiffel language is now supported. The suffix has also beenused 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).

    http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/J_Sharphttp://en.wikipedia.org/wiki/A_Sharp_(.NET)http://en.wikipedia.org/wiki/Ada_(programming_language)http://en.wikipedia.org/wiki/Functional_programminghttp://en.wikipedia.org/wiki/F_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/EiffelStudiohttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Eiffel_(programming_language)http://en.wikipedia.org/wiki/Library_(computing)http://en.wikipedia.org/wiki/Gtk_Sharphttp://en.wikipedia.org/wiki/Wrapper_patternhttp://en.wikipedia.org/wiki/GTK+http://en.wikipedia.org/wiki/GNOMEhttp://en.wikipedia.org/wiki/Cocoa_Sharphttp://en.wikipedia.org/wiki/Cocoa_(API)http://en.wikipedia.org/w/index.php?title=Qt_Sharp&action=edit&redlink=1http://en.wikipedia.org/wiki/Qt_(toolkit)http://en.wikipedia.org/wiki/Qt_(toolkit)http://en.wikipedia.org/w/index.php?title=Qt_Sharp&action=edit&redlink=1http://en.wikipedia.org/wiki/Cocoa_(API)http://en.wikipedia.org/wiki/Cocoa_Sharphttp://en.wikipedia.org/wiki/GNOMEhttp://en.wikipedia.org/wiki/GTK+http://en.wikipedia.org/wiki/Wrapper_patternhttp://en.wikipedia.org/wiki/Gtk_Sharphttp://en.wikipedia.org/wiki/Gtk_Sharphttp://en.wikipedia.org/wiki/Library_(computing)http://en.wikipedia.org/wiki/Eiffel_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/EiffelStudiohttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/F_Sharp_(programming_language)http://en.wikipedia.org/wiki/Functional_programminghttp://en.wikipedia.org/wiki/Ada_(programming_language)http://en.wikipedia.org/wiki/A_Sharp_(.NET)http://en.wikipedia.org/wiki/J_Sharphttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/File:C_sharp_music.svghttp://en.wikipedia.org/wiki/File:C_sharp_music.svg
  • 7/31/2019 ChaRina Power p . .

    5/77

    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 theC:\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 thatoffer 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.

  • 7/31/2019 ChaRina Power p . .

    6/77

    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,");

  • 7/31/2019 ChaRina Power p . .

    7/77

    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 ofcscc, compile with "cscc -o .exe .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 .exe".

  • 7/31/2019 ChaRina Power p . .

    8/77

    ENVIRONMENT OF CSHARPED

  • 7/31/2019 ChaRina Power p . .

    9/77

    Summary of versions

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

    Features

    added

    Generics

    Partial types

    Anonymous methodsIterators

    Nullable types

    Private setters

    (properties)

    Method group

    conversions

    (delegates)

    Implicitly typed

    local variables

    Object and collection

    initializersAuto-Implemented

    properties

    Anonymous types

    Extension methods

    Query expressions

    Lambda expressions

    Expression trees

    Dynamic bindingNamed and optional

    arguments

    Generic co- and

    contravariance

    WindowsRuntime support

    Asynchronous

    methods

    Caller info attributes

    Compiler-as-a-

    service("Roslyn")

    http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Windows_Runtimehttp://en.wikipedia.org/wiki/Windows_Runtimehttp://en.wikipedia.org/wiki/Windows_Runtimehttp://en.wikipedia.org/wiki/Windows_Runtimehttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)
  • 7/31/2019 ChaRina Power p . .

    10/77

    .

    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 thecompiler: 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 returnexactly 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

    http://en.wikipedia.org/wiki/Common_Language_Infrastructurehttp://en.wikipedia.org/wiki/Common_Language_Infrastructurehttp://en.wikipedia.org/wiki/Common_Intermediate_Languagehttp://en.wikipedia.org/wiki/Fortranhttp://en.wikipedia.org/wiki/Variable_shadowinghttp://en.wikipedia.org/wiki/Wikipedia:Avoid_weasel_wordshttp://en.wikipedia.org/wiki/Boolean_data_typehttp://en.wikipedia.org/wiki/Nullable_typehttp://en.wikipedia.org/wiki/Nullable_typehttp://en.wikipedia.org/wiki/Boolean_data_typehttp://en.wikipedia.org/wiki/Wikipedia:Avoid_weasel_wordshttp://en.wikipedia.org/wiki/Variable_shadowinghttp://en.wikipedia.org/wiki/Fortranhttp://en.wikipedia.org/wiki/Common_Intermediate_Languagehttp://en.wikipedia.org/wiki/Common_Language_Infrastructurehttp://en.wikipedia.org/wiki/Common_Language_Infrastructure
  • 7/31/2019 ChaRina Power p . .

    11/77

    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 ofmemory 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.

    http://en.wikipedia.org/wiki/Memory_leakhttp://en.wikipedia.org/wiki/Multiple_inheritancehttp://en.wikipedia.org/wiki/Operator_overloadinghttp://en.wikipedia.org/wiki/Type_safetyhttp://en.wikipedia.org/wiki/Just-in-time_compilationhttp://en.wikipedia.org/wiki/Copy_constructorhttp://en.wikipedia.org/wiki/Copy_constructorhttp://en.wikipedia.org/wiki/Enumerated_typehttp://en.wikipedia.org/wiki/Scope_(programming)http://en.wikipedia.org/wiki/Property_(programming)http://en.wikipedia.org/wiki/Syntactic_sugarhttp://en.wikipedia.org/wiki/Mutator_methodhttp://en.wikipedia.org/wiki/Mutator_methodhttp://en.wikipedia.org/wiki/Attribute_(computing)http://en.wikipedia.org/wiki/Checked_exceptionshttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/First-class_functionhttp://en.wikipedia.org/wiki/Lambda_expressionshttp://en.wikipedia.org/wiki/variablehttp://en.wikipedia.org/wiki/Lambda_expressionshttp://en.wikipedia.org/wiki/First-class_functionhttp://en.wikipedia.org/wiki/First-class_functionhttp://en.wikipedia.org/wiki/First-class_functionhttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Checked_exceptionshttp://en.wikipedia.org/wiki/Attribute_(computing)http://en.wikipedia.org/wiki/Mutator_methodhttp://en.wikipedia.org/wiki/Mutator_methodhttp://en.wikipedia.org/wiki/Mutator_methodhttp://en.wikipedia.org/wiki/Mutator_methodhttp://en.wikipedia.org/wiki/Mutator_methodhttp://en.wikipedia.org/wiki/Mutator_methodhttp://en.wikipedia.org/wiki/Syntactic_sugarhttp://en.wikipedia.org/wiki/Property_(programming)http://en.wikipedia.org/wiki/Scope_(programming)http://en.wikipedia.org/wiki/Enumerated_typehttp://en.wikipedia.org/wiki/Copy_constructorhttp://en.wikipedia.org/wiki/Copy_constructorhttp://en.wikipedia.org/wiki/Just-in-time_compilationhttp://en.wikipedia.org/wiki/Type_safetyhttp://en.wikipedia.org/wiki/Operator_overloadinghttp://en.wikipedia.org/wiki/Multiple_inheritancehttp://en.wikipedia.org/wiki/Multiple_inheritancehttp://en.wikipedia.org/wiki/Memory_leak
  • 7/31/2019 ChaRina Power p . .

    12/77

    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.

    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 outparameter 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 unboundupon method entry, thus it is illegal to reference an outparameter before

    assigning it a value. It also must be assigned by the method in each valid (non-exceptional) code path

    http://en.wikipedia.org/wiki/Name_bindinghttp://en.wikipedia.org/wiki/object_(computer_science)http://en.wikipedia.org/wiki/object_(computer_science)http://en.wikipedia.org/wiki/Name_bindinghttp://en.wikipedia.org/wiki/variable
  • 7/31/2019 ChaRina Power p . .

    13/77

    through the method in order for the method to compile.

    A reference parameter is similar to an outparameter, except that it is boundbefore the method call

    and it need not be assigned by the method.

    Aparams parameter represents a variable number of parameters. If a method signature includes one,

    theparams 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 theparameters 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

    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.

    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.

  • 7/31/2019 ChaRina Power p . .

    14/77

    Escape Sequence Meaning

    \' Single Quote

    \" Double Quote

    \\ Backslash

    \0 Null, not the same as the C# null value

    \a Bell

    \b Backspace

    \f form Feed

    \n Newline\r Carriage Return

    \t Horizontal Tab

    \v Vertical Tab

    CHARACTER ESCAPE SEQUENCES

    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".

  • 7/31/2019 ChaRina Power p . .

    15/77

    Category (by precedence) Operator(s) Associativity

    Primary

    x.y f(x) a[x] x++ x--

    new typeof default checked unchecked delegate

    left

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

    Multiplicative * / % left

    Additive + - left

    Shift > left

    Relational < > = is as leftEquality == != right

    Logical AND & left

    Logical XOR ^ left

    Logical OR | left

    Conditional AND && left

    Conditional OR || leftNull Coalescing ?? left

    Ternary ?: right

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

    right

    OPERATORS WITH THEIR PRECEDENCE AND

    ASSOCIATIVITY

  • 7/31/2019 ChaRina Power p . .

    16/77

    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.)

  • 7/31/2019 ChaRina Power p . .

    17/77

    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:

  • 7/31/2019 ChaRina Power p . .

    18/77

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

  • 7/31/2019 ChaRina Power p . .

    19/77

    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 typedlanguage. 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:

  • 7/31/2019 ChaRina Power p . .

    20/77

    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 forSystem.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.

    http://en.wikipedia.org/wiki/Common_Type_Systemhttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Common_Type_System
  • 7/31/2019 ChaRina Power p . .

    21/77

    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 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 { void Add(T input) { } } class TestGenericList { private

    class ExampleClass { } static void Main() { // Declare a list of type int. GenericList list1 = new

    GenericList(); // Declare a list of type string. GenericList list2 = new GenericList(); //

    Declare a list of type ExampleClass. GenericList list3 = new GenericList(); } }

    http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Type_conversionhttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Generic_programminghttp://en.wikipedia.org/wiki/Generic_programminghttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Type_conversionhttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_Sharp_(programming_language)
  • 7/31/2019 ChaRina Power p . .

    22/77

    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 }

    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) {} }

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

    http://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/C_preprocessorhttp://en.wikipedia.org/wiki/C_preprocessorhttp://en.wikipedia.org/wiki/Symbol_(programming)http://en.wikipedia.org/wiki/Code_foldinghttp://en.wikipedia.org/wiki/Comment_(computer_programming)http://en.wikipedia.org/wiki/C++http://en.wikipedia.org/wiki/C_(programming_language)http://en.wikipedia.org/wiki/Common_Language_Infrastructurehttp://en.wikipedia.org/wiki/Common_Language_Infrastructurehttp://en.wikipedia.org/wiki/Common_Language_Infrastructurehttp://en.wikipedia.org/wiki/C_(programming_language)http://en.wikipedia.org/wiki/C++http://en.wikipedia.org/wiki/Comment_(computer_programming)http://en.wikipedia.org/wiki/Code_foldinghttp://en.wikipedia.org/wiki/Symbol_(programming)http://en.wikipedia.org/wiki/C_preprocessorhttp://en.wikipedia.org/wiki/C_preprocessorhttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)
  • 7/31/2019 ChaRina Power p . .

    23/77

    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 modifiersconst - 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.

  • 7/31/2019 ChaRina Power p . .

    24/77

    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 thevariable'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 ofpublic, protected, internal, protected internal, or private (from most visible

    to least visible).

    Local variablesLike 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

  • 7/31/2019 ChaRina Power p . .

    25/77

    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'senvironment 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.

    Aparams 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 typesBecause 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

  • 7/31/2019 ChaRina Power p . .

    26/77

    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 israrely a need to know the actual size of a reference type.

  • 7/31/2019 ChaRina Power p . .

    27/77

    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

  • 7/31/2019 ChaRina Power p . .

    28/77

    Floating-pointC# Alias .NET Type Size (bits) Precision Range

    float System.Single 32 7 digits 1.5 x 10-45to 3.4 x 1038

    double System.Double 64 15-16 digits 5.0 x 10-324to 1.7 x 10308

    decimal System.Decimal 128 28-29 decimal places 1.0 x 10-28to 7.9 x 1028

    Other predefined typesC# Alias .NET Type Size (bits) Rangebool System.Boolean 32 true or false, which aren't related to any integer in C#.

    object System.Object 32/64 Platform dependant (a pointer to an object).

    string System.String 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)

    {

  • 7/31/2019 ChaRina Power p . .

    29/77

    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 statementThe 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 unconditionalreturn 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; }

  • 7/31/2019 ChaRina Power p . .

    30/77

    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) { ... }

  • 7/31/2019 ChaRina Power p . .

    31/77

    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

  • 7/31/2019 ChaRina Power p . .

    32/77

    p y g (), pp g y

    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)

    http://en.wikipedia.org/wiki/Call_stackhttp://en.wikipedia.org/wiki/Call_stack
  • 7/31/2019 ChaRina Power p . .

    33/77

    j p g g ( )

    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 classAll 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 itreturns 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.

    http://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Object-oriented_programming
  • 7/31/2019 ChaRina Power p . .

    34/77

    Default constructor Finalizer Member initialization Inheritance

    Classesnot required (auto

    generated)yes not required

    yes (if base class is not

    sealed)

    Structsrequired (not auto

    generated)no required not supported

    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 allocatedon 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 fromSystem.ValueType, that inherits from System.Object. Structs are more suitable for smaller constructs of data.

    This is a short summary of the differences:

    Declaration

    http://en.wikipedia.org/wiki/Class_(computer_science)http://en.wikipedia.org/wiki/Structure_(computer_science)http://en.wikipedia.org/wiki/Structure_(computer_science)http://en.wikipedia.org/wiki/Class_(computer_science)
  • 7/31/2019 ChaRina Power p . .

    35/77

    Declaration

    A class is declared like this:

    class Foo { // Member declarations }

    Partial class

    This is a feature ofC# 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 ofC# 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;

    http://en.wikipedia.org/wiki/C_Sharp_2.0http://en.wikipedia.org/wiki/C_Sharp_3.0http://en.wikipedia.org/wiki/C_Sharp_3.0http://en.wikipedia.org/wiki/C_Sharp_2.0
  • 7/31/2019 ChaRina Power p . .

    36/77

    Collection initializers

    This is a feature ofC# 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 list = new List {2, 5, 6, 6 }; // Equal to List list = new List(); 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 pointerIn 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

    http://en.wikipedia.org/wiki/C_Sharp_3.0http://en.wikipedia.org/wiki/C_Sharp_3.0
  • 7/31/2019 ChaRina Power p . .

    37/77

    Constraint Explanation

    where T : structtype parameter must be avalue type

    where T : classtype parameter must be areference type

    where T : new()

    type parameter must havea constructor with noparameters (must appearlast)

    where T : type parameter mustinherit from

    where T : type parameter must be, ormust implement thisinterface

    where T : Unaked type parameter

    constraint

    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:

  • 7/31/2019 ChaRina Power p . .

    38/77

    Covariance and contravariance

    This is a feature ofC# 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 has been redefined as follows:

    interface IEnumerable { IEnumerator GetEnumerator(); }

    Therefore, any class that implements IEnumerable for some class Derived is also considered to

    be compatible with IEnumerable 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 objects) { foreach (object o in objects) { System.Console.WriteLine(o);

    } } IEnumerable strings = new List(); PrintAll(strings); // IEnumerable is implicitly

    converted to IEnumerable

    For contravariance, the existing interface IComparer has been redefined as follows:

    public interface IComparer { int Compare(T x, T y); }

    Therefore, any class that implements IComparer for some class Base is also considered to be

    compatible with IComparer for all classes and interfaces Derived that are extended from Base.

    It makes it possible to write code such as:

    IComparer objectComparer = GetComparer(); IComparer stringComparer =objectComparer;

    http://en.wikipedia.org/wiki/C_Sharp_4.0http://en.wikipedia.org/wiki/.NET_Framework_4.0http://en.wikipedia.org/wiki/Generic_programminghttp://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)http://en.wikipedia.org/wiki/Generic_programminghttp://en.wikipedia.org/wiki/.NET_Framework_4.0http://en.wikipedia.org/wiki/C_Sharp_4.0
  • 7/31/2019 ChaRina Power p . .

    39/77

    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 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");

    http://en.wikipedia.org/wiki/Foreachhttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Generic_programminghttp://en.wikipedia.org/wiki/.NET_Frameworkhttp://en.wikipedia.org/wiki/.NET_Frameworkhttp://en.wikipedia.org/wiki/Generic_programminghttp://en.wikipedia.org/wiki/C_Sharp_(programming_language)http://en.wikipedia.org/wiki/Foreach
  • 7/31/2019 ChaRina Power p . .

    40/77

    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 "///".

    /// documentation here

    This is the most recommended type. Avoid using butterfly style comments. For example:

    //**************************// Butterfly style documentation comments like this are not recommended.

    Inheritance polymorphism

  • 7/31/2019 ChaRina Power p . .

    41/77

    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.

    ArraysAlthough 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] ;

  • 7/31/2019 ChaRina Power p . .

    42/77

    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

    h f ll h d ( d b h " l "

  • 7/31/2019 ChaRina Power p . .

    43/77

    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 itsoperators 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

    ofinteger 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 placedafter 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 placedbefore 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 performedbitwise.

    a && b a and b The binary operator && operates on boolean operands only. It evaluates its first

    d If h l i f l i f l O h i i l d h l f h d

  • 7/31/2019 ChaRina Power p . .

    44/77

    operand. If the result isfalse, 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 isgreater 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 ifa 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.

  • 7/31/2019 ChaRina Power p . .

    45/77

    Bitwise shiftingSample usage Read Explanation

    a b a right shift b The binary operator >> evaluates its operands and returns theresulting 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 high-

    order bits to the sign bit of the first argument, or to zero if the first argument is unsigned.

    Relational

    The binary relational operators ==, !=, , = are used for relational operations and for

    type comparisons.Sample usage Read Explanation

    a == b a is equal to b For arguments ofvalue 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

  • 7/31/2019 ChaRina Power p . .

    46/77

    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 resultsto (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 aoperator= b, resulting in less typing and neater syntax.Sample usage Read Explanation

    a += b aplus equals (or increment by) b Equivalent to a = a + b.

    a -= b a minus equals (or decrement by) b Equivalent to a = a - b.

    a *= b a multiply equals (or multiplied by) b Equivalent to a = a * b.

    a /= b a divide equals (or divided by) b Equivalent to a = a / b.

    % b d l b E i l t t % b

  • 7/31/2019 ChaRina Power p . .

    47/77

    a %= b a mod equals b Equivalent to a = a % b.

    a &= b a and equals b Equivalent to a = a & b.

    a |= b a or equals b Equivalent to a = a | b.

    a ^= b a xor equals b Equivalent to a = a ^ b.

    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 valuetypes, 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

  • 7/31/2019 ChaRina Power p . .

    48/77

    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()

    {

  • 7/31/2019 ChaRina Power p . .

    49/77

    {

    }

    }

    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 haveparameters. 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

  • 7/31/2019 ChaRina Power p . .

    50/77

    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

  • 7/31/2019 ChaRina Power p . .

    51/77

    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 offields.

    They simplify the syntax of calling traditional get and set methods (a k a accessor methods) Like

  • 7/31/2019 ChaRina Power p . .

    52/77

    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 3public 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.

  • 7/31/2019 ChaRina Power p . .

    53/77

    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 ex