c sharp by nikhil

Upload: nikhil-thakur

Post on 07-Apr-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 c Sharp by Nikhil

    1/40

    C Sharp by NIKHIL

    1

    C# : C Sharp

    1) Introduction to .NET2) An Introduction To The .NET Framework3) C# System Requirements4) Application Types in C#5) To Begin With C# Programming6) C# Types7) Predefined Reference Types8) Data types in C#9) Classes and Object Model in .NET10) Property in C# class11) Method Overloading in C#12) C# Tutorial Namespaces13) Interfaces in C#14) Delegates in C#15) Events in C#16) Reflection in C#

  • 8/6/2019 c Sharp by Nikhil

    2/40

    C Sharp by NIKHIL

    2

    Introduction to .NET

    Introduction:

    Before we start explaining what .Net is? Lets discuss about Internet on business organization.

    There are three phases of Internet.

    y First phase starts early in 1990s, which brought big revolution. Organizations created and

    launched their websites. The core idea behind this is to know hit rate means how many peoples

    are interested in their product and services. So that they can update their products accordingly.

    y The 2nd is in which we are right now. Organization is generating revenues from on-line trading.

    y We are moving into 3rd phase and here idea is to communicate peoples, partner and share

    resources which are geographically far to run business successfully.

    Here .net comes into picture, which is designed by Microsoft people, which provide to build

    net based application which connect peoples and data at remote locations through any devices

    (i.e. laptop, mobiles, and pda)

    What is .net basically?

    NET is the Microsoft Web services strategy to connect information, people, systems, anddevices through software. Integrated across the Microsoft platform, .NET technology

    provides the ability to quickly build, deploy, manage, and use connected, security-enhancedsolutions with Web services. .NET-connected solutions enable businesses to integrate their

    systems more rapidly and in a more agile manner and help them realize the promise ofinformation anytime, anywhere, on any device.

    The Microsoft platform includes everything a business needs to develop and deploy a Webservice-connected IT architecture: servers to host Web services, development tools to create

    them, applications to use them, and a worldwide network of more than 35k Microsoft

    Certified Partner organizations to provide any help we need.

  • 8/6/2019 c Sharp by Nikhil

    3/40

    C Sharp by NIKHIL

    3

    An Introduction To The .NET Framework

    .NET Framework

    .NET is Microsofts new strategy for the development and deployment of software.

    Depending on your interests and development background, we may already have a number of

    preconceived notions regarding

    y NET fundamentally changes the way applications execute under the Windows OperatingSystem.

    y with .NET Microsoft is, in effect, abandoning its traditional Way of applicationdevelopment, one which favors compiled components, and is embracing Interpreted

    technology (similar, in many ways, to the Java Paradigm).y NET brings about significant changes to both C++ and Visual Basic, and introduces a new

    language called C# .

    y NET is built from the ground up with the Internet in mind, embracing open Internetstandards such as XML and HTTP.

    The .NET Framework can be distilled into the following three entities:

    The Time-wasters will surround you all the sides and will tear away at your minutes and

    hours, holding the back from producing a critical results which are vital to the success in thecareer.

    y The Common Language Runtime (CLR)CLR is execution environment for all programs in the .NET Framework. The CLR is

    similar to a Java Virtual Machine (VM) in that it interprets byte code and executes it on the

    fly, while simultaneously providing services such as garbage collection and exception

    handling. Unlike a Java VM, which is limited to the Java language, the CLR is accessible

    from any compiler that produces Microsoft Intermediate Language (IL) code, which is

    similar to Java byte code. Code that executes inside the CLR is referred to as managed

    code. Code that executes outside its boundaries is called unmanaged code.

    USER INTERFACE ANDWINDOWS FORM

    BASE CLASS LIBRARIES

    COMMON LANGUAGE RUNTIME

  • 8/6/2019 c Sharp by Nikhil

    4/40

    C Sharp by NIKHIL

    4

    . Net framework

    y The Base class librariesIt provides hundreds of prewritten services that user uses. These classes are the building blocks for

    .NET applications. Every language had its own unique supporting libraries, accessible only from

    that particular language. This library includes UI,Data, Web, Diagonostic, and Ado.

    y User interface and Win formsThis includes ASP.net pages or windows forms to interact with the application.

  • 8/6/2019 c Sharp by Nikhil

    5/40

    C Sharp by NIKHIL

    5

    System Requirements

    System Requirements

    In order to install the .NET Framework on your machine, Microsoft recommends the

    following system configuration:

    y Processor: Minimum Pentium II-450Mhz (Pentium III-650Mhz recommended).y Operating System: Windows 2000 (Server or Professional), Windows XP, or Windows NT

    4.0 Server.

    y Memory: 96 MB (128 MB recommended) for Windows 2000 Professional, 192MB (256MB recommended) for Windows 2000 server.

    y Hard drive: 500MB free on the drive where the OS is installed (usually C:\) and 2.5 Gigsfree on the installation drive (where VS.NET will be installed)..

  • 8/6/2019 c Sharp by Nikhil

    6/40

    C Sharp by NIKHIL

    6

    An introduction to C# (pronounced "C sharp")C# (pronounced "C sharp") is a simple, modern, object-oriented, and type-safe

    programming language. It will immediately be familiar to C and C++ programmers. C#

    combines the high productivity of Rapid Application Development (RAD) languages.

    Visual C# .NET is Microsoft's C# development tool. It includes an interactive

    development environment, visual designers for building Windows and Web applications, a

    compiler, and a debugger. Visual C# .NET is part of a suite of products, called Visual

    Studio .NET, that also includes Visual Basic .NET, Visual C++ .NET, and the JScript

    scripting language. All of these languages provide access to the Microsoft .NET

    Framework, which includes a common execution engine and a rich class library. The

    .NET Framework defines a "Common Language Specification" (CLS), a sort of lingua

    franca that ensures seamless interoperability between CLS-compliant languages and classlibraries. For C# developers, this means that even though C# is a new language, it hascomplete access to the same rich class libraries that are used by seasoned tools such as

    Visual Basic .NET and Visual C++ .NET. C# itself does not include a class library

    Features of c#:

    As a new programming language following features made this different from other

    languages: -

    y Simpley Type safey Versioning: making new version of an application from existing one to work.y Follows all OOPs paradigmy Automatic garbage collectiony Flexible

    What c# has added?

    As compared to c++, following concepts are added into c: -

    y Assembliesy Versioningy Indexersy Boxing

  • 8/6/2019 c Sharp by Nikhil

    7/40

    C Sharp by NIKHIL

    7

    y Delegates

    Application Types in C#

    Application Types in C#

    Class Library Creates a project for creating classes that can be

    used in other applications.

    Console Application Creates a Visual C# application with a command-line

    interface.

    ASP.NET Web

    Application

    Creates a Visual C# application with a Web user

    interface.

    ASP.NET Web Service Creates an XML Web service with Visual C# that other

    applications can access.

    ASP.NET Mobile Web

    Application

    Creates an application viewable on PDAs, cell phones,

    and other mobile devices.

    Empty Project Creates an empty project for creating a local

    application.

    Empty Web Project Creates an empty project for creating a Web

    application.

  • 8/6/2019 c Sharp by Nikhil

    8/40

    C Sharp by NIKHIL

    8

    To Begin With C# Programming

    To Begin With C# Programming

    C# is a language that provides

    y Simplicity of Visual Basic

    y Power of C++

    y Concentrate on the high-value tasks;

    y Portability of Java

    First C# program to display hello, world on the console

    using System;

    class Hello

    {

    static void Main ()

    {

    Console.WriteLine("hello, world");

    }

    }

    The source code for a C# program is typically stored in one or more text files with a file

    extension of .cs, as in hello.cs. Using the command-line compiler provided with Visual

    Studio .NET, such a program can be compiled with the command-line directive

    csc hello.cs , which produces an application, named hello.exe. The output produced by

    this application when it is run is:

    hello, world

    The using System; directive references a namespace called System that is provided by the

    Microsoft .NET Framework class library. This namespace contains the Console class

    referred to in the Main method. Namespaces provide a hierarchical means of organizing

  • 8/6/2019 c Sharp by Nikhil

    9/40

    C Sharp by NIKHIL

    9

    the elements of one or more programs. A "using" directive enables unqualified use of the

    types that are members of the namespace. The "hello, world" program uses Console.

    WriteLine as shorthand forSystem.Console.WriteLine.

    The Main method is a member of the class Hello. It has the static modifier, and so it is amethod on the class Hello rather than on instances of this class. The entry point for an

    application the method that is called to begin execution is always a static methodnamed Main. The "hello, world" output is produced using a class library. The language

    does not itself provide a class library. Instead, it uses a class library that is also used by

    Visual Basic .NET and Visual C++.NET.

    The program does not use a global method for Main. Methods and variables are not

    supported at the global level; such elements are always contained within type declarations

    (e.g., class and struct declarations).

    C# language does not use either "::" or "->" operators. The "::" is not an operator at all,

    and the "->" operator is used in only a small fraction of programs those that employ

    unsafe code. The separator "." is used in compound names such as Console. WriteLine.

    The program does not contain forward declarations. Forward declarations are neverneeded, as declaration order is not significant. C# does not use #include to import program

    text. Dependencies among programs are handled symbolically rather than textually. This

    approach eliminates barriers between applications written using multiple languages.

  • 8/6/2019 c Sharp by Nikhil

    10/40

    C Sharp by NIKHIL

    10

    .NET Type

    TYPE:

    C# supports two kinds of types: value types and reference types. Value types include simpletypes (e.g., char, int, and float), enum types, and struct types.

    Reference types include class types, interface types, delegate types, and array types.

    Value types differ from reference types in that variables of the value types directly contain

    their data, whereas variables of the reference types store references to objects. With reference

    types, it is possible for two variables to reference the same object, and thus possible for

    operations on one variable to affect the object referenced by the other variable. With valuetypes, the variables each have their own copy of the data, and it is not possible for operations

    on one to affect the other. The example

    The example using System;

    class Class1

    {

    public int Value = 0;

    }class Test

    {

    static void Main ()

    {

    int val1 = 0;

    int val2 = val1;

    val2 = 123;

    Class1 ref1 = new Class1();

    Class1 ref2 = ref1;

    ref2.Value = 123;

    Console.WriteLine("Values: {0}, {1}", val1, val2);

    Console.WriteLine("Refs: {0}, {1}", ref1.Value, ref2.Value);

    }

    }

    The output produced is

  • 8/6/2019 c Sharp by Nikhil

    11/40

    C Sharp by NIKHIL

    11

    Values: 0, 123 Refs: 123, 123

    The lines

    Console.WriteLine ("Values: {0}, {1}", val1, val2);

    Console.WriteLine ("Refs: {0}, {1}", ref1. Value, ref2. Value);

    The first argument is a string, which may contain numbered placeholders like {0} and {1}.

    Each placeholder refers to a trailing argument with {0} referring to the second argument, {1}

    referring to the third argument, and so on. Before the output is sent to the console, eachplaceholder is replaced with the formatted value of its corresponding argument

    Developers can define new value types through enum and struct declarations, and can definenew reference types via class, interface, and delegate declarations.

    Eliminating the Time Wasters

    The Time-wasters will surround you all the sides and will tear away at your minutes andhours, holding the back from producing a critical results which are vital to the success in the

    career.

    y Eliminate a time wasters in life;

    y The Law of an Excluded Alternative;

    y Identify a major time-wasters;

    y Practical ways to overcome and avoid them if possible.

  • 8/6/2019 c Sharp by Nikhil

    12/40

    C Sharp by NIKHIL

    12

    Predefined Reference Types

    Predefined Reference Types

    The predefined reference types are object and string. The type object is the ultimate base typeof all other types. The type string is used to represent Unicode string values. Values of type

    string are immutable.

    Object

    The ultimate base type of all other types object o = null;

    string

    String type; a string is a sequence ofUnicode characters string s = "hello";

    Predefined value types

    The predefined value types include signed and unsigned integral types, floating-point types,

    and the types bool, char, and decimal. The signed integral types are sbyte, short, int, and long;the unsigned integral types are byte, ushort, uint, and ulong; and the floating-point types are

    float and double.

    y Eliminate a time wasters in life;

    y The Law of an Excluded Alternative;

    y Identify a major time-wasters;

    y Practical ways to overcome and avoid them if possible.

    sbyte 8-bit signed integral type sbyte val = 12;

    short 16-bit signed integral type short val = 12;

    int 32-bit signed integral type int val = 12;

    long 64-bit signed integral type long val1 = 12;

  • 8/6/2019 c Sharp by Nikhil

    13/40

    C Sharp by NIKHIL

    13

    long val2 = 34L;

    byte 8-bit unsigned integral type byte val1 = 12;

    ushort 16-bit unsigned integral type ushort val1 = 12;

    uint 32-bit unsigned integral type uint val1 = 12;

    float Single-precision floating point type float val = 1.23F;

    doubleDouble-precision floating point type double val1 = 1.23;

    double val2 = 4.56D;

    Bool

    The bool type is used to represent Boolean values: values that are either true or false. The

    inclusion of bool makes it easier to write self-documenting code, and also helps eliminate theall-too-common C++ coding error in which a developer mistakenly uses "=" when "=="

    should have been used. In C#, the example

    int i =;

    F (i);

    if (i = 0) // the test should be (i == 0)

    G();

    results in a compile-time error because the expression i = 0 is of type int,

    and if statements require an expression of type bool.

    Boolean type;

    a bool value is either true or false

    bool val1 = true;

    bool val2 = false;

    char

    The char type is used to represent Unicode characters. A variable of type char represents a

  • 8/6/2019 c Sharp by Nikhil

    14/40

    C Sharp by NIKHIL

    14

    single 16-bit Unicode character. Character type; a char value is a Unicode character char val= 'h';

    Decimal

    The decimal type is appropriate for calculations in which rounding errors caused by floating

    point representations are unacceptable. Common examples include financial calculations such

    as tax computations and currency conversions. The decimal type provides 28 significant

    digits.

    Precise decimal type with 28 significant digits

    decimal val = 1.23M;

    Each of the predefined types is shorthand for a system-provided type. For example, the

    keyword int refers to the struct System.Int32. As a matter of style, use of the keyword is

    favored over use of the complete system type name.

    Two expressions of type int are considered equal if they represent the same integer value.

    Two expressions of type object are considered equal if both refer to the same object, or if

    both are null. Two expressions of type string are considered equal if the string instances have

    identical lengths and identical characters in each character position, or if both are null.

    Differences between Values Types and Reference Types.

    The following table shows some of the differences between values types and reference types.

    Value types Reference types

    Allocated on stack Allocated on heap

    A value type variable contains the

    data itself

    Reference type variable contains the address of memory

    location where data is actually stored

    When we copy a value type variable

    to another one, the actual data is

    copied and each variable can be

    independently manipulated.

    When copying a reference type variable to another

    variable, only the memory address is copied. Both

    variables will still point to the same memory location,

    which means, if we change one variable, the value will bechanged for the other variable too.

    integer, float, boolean, double etc are

    value types.string and object are reference types.

    struct is value type. Classes and interfaces are reference types.

  • 8/6/2019 c Sharp by Nikhil

    15/40

    C Sharp by NIKHIL

    15

    Data types in C# and .NET

    Data types in C# and .NET

    Data Types are the basic building block of any language.

    Microsoft has tried to standardize the data types in .NET framework by introducing a limited, fixed

    set of types that can be used to represent almost anything in programming world.

    C++ was very rich in data types, but that leads to confusion too. Especially, when we write

    components that may be consumed by applications written in other platforms, we have tomake sure the types used are compatible with other platforms too!

    NET types start from a clean slate. All .NET languages share the same types. So, they areall compatible and no worries. This means, we can call C# code from VB.NET and vice

    versa, without worrying about type conversions.

    NET data types are either structures or classes, part of the System namespace. For example,the following data types are implemented as struct in .NET:

    y Int16

    y Int32

    y Double

    (String is implemented as a class in .NET.)If you are not very familiar with struct and class, don't worry about it. We can just use them

    as if they are simple data types.

    Here is how we can declare variables of type Int, Double and String:

    y Int16 age, employee Number;

    y Double salary;

    y String name, address;

    we can use any of the .NET data types directly in any .NET language - in C#, VB.NET or

    xyz. NET. But in addition to the .NET types, each language provides a set of primitivetypes, which map to the corresponding types in .NET class library. This is why we may see

    some people use string and some others use String. There is no big difference. string is aprimitive data type in C# and String is the corresponding class in .NET class library. The

    string in C# is mapped to the class in .NET class library. So, whether we use string orString, there is no real difference.

  • 8/6/2019 c Sharp by Nikhil

    16/40

    C Sharp by NIKHIL

    16

    Data Types in C# and the corresponding class/struct in .NET class library

    The following list shows the list of data types available in C# and their corresponding

    class/struct in .NET class library.

    C# Data type Mapped to .NET class/struct

    sbyte System.SByte

    byte System.Byte

    char System.Char

    float System.Single

    decimal System.Decimal

    double System.Double

    ushort System.UInt16

    short System.Int16

    uint System.UInt32

    int System.Int32

    ulong System.UInt64

    long System.Int64

  • 8/6/2019 c Sharp by Nikhil

    17/40

    C Sharp by NIKHIL

    17

    bool System.Boolean

    string System.String

    object System.Object

  • 8/6/2019 c Sharp by Nikhil

    18/40

    C Sharp by NIKHIL

    18

    Classes and Object Model in .NET

    Classes and Object Model in .NET

    We will start with an introduction to what is object oriented programming, how to write

    simple classes, creating objects etc.

    What is a class?

    In modern object oriented programming, large computer programs are divided into several'classes'. Typically, a large project will have several hundred classes. A class represents an

    entity in a program.

    For example, if we are doing a small program called calculator, we will typically have asingle (or more) class called 'Calculator' .The class will have several methods that will do

    the functionality of the class

    So, our calculator may have methods like the following:

    y Add ()

    y Subtract ()

    y Multiply ()

    y Divide ()

    Here is a sample calculator class, written in C# :

    using System;

    public class Calculator

    {

    public int Add(int value1, int value2)

    {

    return value1 + value2;

    }

    public int Subtract(int value1, int value2)

    {

    return value1 - value2;

    }

  • 8/6/2019 c Sharp by Nikhil

    19/40

    C Sharp by NIKHIL

    19

    public int Multiply(int value1, int value2)

    {

    return value1 * value2;

    }

    public int Divide(int value1, int value2)

    {

    return value1 / value2;

    }

    }

    Methods

    Any class in an object-oriented language has method and property members. These are the

    places where the actual business logic or functionality is written and executed. Method isobject-oriented item of any language. All C# programs are constructed from a number of

    classes and almost all the classes will contain methods. A class when instantiated is called anobject. Object-oriented concepts of programming say that the data members of each object

    represent its state and methods represent the object behavior.

    Method Signature in C#: Each method is declared as follows:

    Return-type methodname ( Parameterslist );

    For better understanding of methods let consider following example. We have a class Man. Itcan have many fields like that:

    public class Man

    {

    public Man(){}

    private int m_old;

    private string m_name;

    public string WhatIsYourName()

    {

    Console.WriteLine(m_name);

    return m_name;

    }

    public string HowOldAreYou()

    {

    Console.WriteLine(m_old.ToString());

    return m_old;

    }

  • 8/6/2019 c Sharp by Nikhil

    20/40

  • 8/6/2019 c Sharp by Nikhil

    21/40

    C Sharp by NIKHIL

    21

    example for the declaration of a function with variable argument signature is as follows.

    Public void functionName(int a, params int[] varParam);

    Property in C# class

    Property in C# class

    How do we access member variables of any class from outside the class? In most of the

    languages including C++, we will make the member variables public so that we can

    create an instance of the class and directly access the public fields, as shown below:

    using System;class Hello

    {

    static void Main () {

    Console.WriteLine("hello, world");

    }

    }

    The above class has one public field: color. We may access this field from outside theclass as shown below:

    Car car = new Car ();

    car. Color = "red";

    string color = car.color;

    But this is the old way ! This would still work with C#, but the suggested approach is to

    use "Property" instead of directly accessing member variables.

    The following code snippet shows how to create "Property" in a class.

    public class Car

    {

    // private fields.

    private string color;

    // constructor

    public Car()

    {

  • 8/6/2019 c Sharp by Nikhil

    22/40

    C Sharp by NIKHIL

    22

    }

    public string Color

    {

    get

    {

    return color; // return the value from privte field.

    }

    set

    {

    color = value; // save value into private field.

    }

    }

    }

    The above class has one private field - color. Then we have one "Property" called'Color', which is used to represent the private field. Note that the field is private and the

    Property is public. (We have used the same name with upper/lower case to represent the'Property' and 'field', but we may give any name we want.)

    Each property has two parts:

    y get

    y set

    The get part is executed when we access the value of the Property as shown below:

    Car car = new Car();

    string color = car.Color;

    When executed, the above get accessor will return the value stored in the field 'color'.

    The set part is executed when we assign a value to the Property as shown below:

    Car car = new Car();

    car.Color = "RED

    ";

    When executed, the above set accessor will assign the value "RED" to the private field

    'color'. (Note that 'value' is a keyword, which will have the value assigned to it.)

  • 8/6/2019 c Sharp by Nikhil

    23/40

    C Sharp by NIKHIL

    23

    So, what is the difference ?

    On the first look, there is no difference! We can achieve the same behaviour by writing

    2 different methods ( like SetColor(...), GetColor() ).

    First advantage of using property is, code looks cleaner than having 2 separate methods.

    We can simply call a property as if it was a field in the class.

    Well, then we may ask why make it 2 methods, we can make it a public field, so that we

    can access it by creating an instance of the class.

    The main advantage over using a Property instead of a public field is, with the property,we will get a chance to write few lines of code (if we want) in the get and set accessors.

    So, we can perform some validation or any other logic before returning any values orassigning to the private field. See the modified class below:

    public class Car{

    // private fields.

    private string color;

    // constructor

    public Car()

    {

    }

    public string Color

    {

    get

    {

    if ( color == "" )

    return "GREEN";

    else

    return color;

    }

    set

    {

    if ( value == "" )thrown new Exception ("Wrong value.");

    else

    color = value;

    }

    }

  • 8/6/2019 c Sharp by Nikhil

    24/40

    C Sharp by NIKHIL

    24

    }

    Let us analyze the get part first. Here we are checking whether there is a valid value in

    the field 'color' before we return the value. If it is empty, we are getting a chance to

    return a default value 'Green'. This way, we can make sure that whoever calls theproperty 'Color' will always get a valid color, never an empty string.

    In the set part, we are doing a validation to make sure we always assign a a valid value

    to our field. If someone assign an empty string to the 'Color' property, he will get an

    exception (error).

    Car car = new Car();

    car.Color = "";

    The above code will throw an error because we are trying to assign an empty string and

    the set accessor will throw an error if it an empty string. This way, we can make surethat we allow only valid values to be assigned.

    So, i guess now you would appreciate the purpose of "Property". So, no more public

    fields! Always have private fields and write public properties as wrapper for them if

    required to expose them to outside the class.

  • 8/6/2019 c Sharp by Nikhil

    25/40

    C Sharp by NIKHIL

    25

    Arrays

    Arrays

    C# arrays are reference types. The size of the array is not part of the array type

    int[] row;

    int[,] grid;

    Array instances are created using the new keyword. Array elements are default

    initialised to zero (enums and numeric types), false (bool), or null (reference types).

    row = new int[42];

    grid = new int[9,6];

    Array instances can be initialised:

    int[] row = new int[4]{ 1, 2, 3, 4 }; // longhand

    int[] row = { 1, 2, 3, 4 }; // shorthand

    row = new int[4]{ 1, 2, 3, 4 }; // okay

    row = { 1, 2, 3, 4 }; // compile time error

    Array indexes start at zero and all array accesses are bounds checked

    (IndexOutOfRangeException). All arrays implicitly inherit from the System.Array

    class. This class brings array types into the CLR and provides some handy properties

    and methods:

    namespace System

    {

    public abstract class Array : .

    .. {

    ...

    public int Length { get { ... } }public int Rank { get { ... } }

    public int GetLength(int rank) { ... }

    public virutal IEnumerator GetEnumerator() { ... }

    ...

    }

  • 8/6/2019 c Sharp by Nikhil

    26/40

    C Sharp by NIKHIL

    26

    }

    Whatare Jagged Arrays in C#?

    A special type of array is introduced in C#. A Jagged Array is an array of an array in

    which the length of each array index can differ.

    Example: A Jagged Array can be used is to create a table in which the lengths of the

    rows are not same. This Array is declared using square brackets ( [ ] ) to indicate eachdimension.

    The following code demonstrates the creation of a two-dimensional jagged array.

    Class Jagged

    {

    public static void Main()

    {

    int [][] jagged=new int [3][];

    jagged[0]=mew int[4]

    jagged[1]=mew int[3]

    jagged[2]=mew int[5]

    int I;

    Storing values in first array

    for (I=0;I

  • 8/6/2019 c Sharp by Nikhil

    27/40

    C Sharp by NIKHIL

    27

    for (I=0;I

  • 8/6/2019 c Sharp by Nikhil

    28/40

    C Sharp by NIKHIL

    28

    Method Overloading

    Method Overloading

    In complex applications written in C#, we may need many methods which do

    essentially similar functions but are just different enough to be considered unique.

    For example, we may have to calculate a person's tax liability and would need to

    implement a method for doing this calculation in our application program.

    However, there are many different rules when it comes to tax calculations and

    they vary throughout the world. While there may be many rules, one basic

    equation stays the same: Your net income equals your gross income minus a

    computed tax amount. We would probably have to implement different methods

    for each type of tax calculation. And, we could give each method a unique name

    such as TaxCalc1, TaxCalc2, TaxCalc3, etc. But wouldn't it be nice to just name

    the method TaxCalc and pass different arguments to it based on the computationdesired?

    Syntax:

    Public void functionName(int a, params int[] varParam);

    Public void functionName(int a);

    How does C# know which method to call? It's easy. It knows which method to

    invoke based on the number and type of arguments passed to it. This is also

    referred to as the signature of the method. If C# sees you are calling TaxCalc withfour arguments, then it will call that method with four receiving arguments. The

    methods are all very similar however they are differ by the number of arguments

    used in the tax calculation.

  • 8/6/2019 c Sharp by Nikhil

    29/40

    C Sharp by NIKHIL

    29

    Caveat

    It is important to remember that C# determines which method to call based upon

    the method's signature. If you were to define two methods with the same name

    and the same number and type of passed arguments, you would get a compile-time error .

    However, we can have two methods with the same name and the same number ofarguments as long as the argument types differ.

    Method overloading is a powerful concept in C# in that it helps to simplify code

    reusability and clarity. If our example method of TaxCalc was placed in a .dll file

    somewhere, we would only have to remember that I have to call TaxCalc and only

    fill in the appropriate arguments to pass.

  • 8/6/2019 c Sharp by Nikhil

    30/40

    C Sharp by NIKHIL

    30

    Net C# Tutorial Namespaces

    Net C# Tutorial Namespaces

    A Namespace in Microsoft .Net is like containers of objects. They may containunions, classes, structures, interfaces, enumerators and delegates. Main goal of

    using namespace in .Net is for creating a hierarchical organization of program.

    In this case a developer does not need to worry about the naming conflicts of

    classes, functions, variables etc., inside a project.

    In Microsoft .Net, every program is created with a default namespace. Thisdefault namespace is called as global namespace. But the program itself can

    declare any number of namespaces, each of them with a unique name. Theadvantage is that every namespace can contain any number of classes, functions,

    variables and also namespaces etc., whose names are unique only inside the

    namespace. The members with the same name can be created in some other

    namespace without any compiler complaints from Microsoft .Net.

    To declare namespace C# .Net has a reserved keyword namespace. If a new

    project is created in Visual Studio .NET it automatically adds some global

    namespaces. These namespaces can be different in different projects. But each

    of them should be placed under the base namespace System. The names space

    must be added and used through the using operator, if used in a different project.

    using System;

    namespace OutNamespace

    {

    namespace WorkNamespace

    { /// can be placed some classes, structures etc.

    }

    }

    this example we create two namespaces. These namespaces have hierarchical

  • 8/6/2019 c Sharp by Nikhil

    31/40

    C Sharp by NIKHIL

    31

    structure. We have some outer one named OutNamespace and the inner one

    called WorkNamespace. The inner namespace is declared with a C# .Net classWorkItem.

    Eliminating the Time Wasters

    The Time-wasters will surround you all the sides and will tear away at your

    minutes and hours, holding the back from producing a critical results which are

    vital to the success in the career.

    y Eliminate a time wasters in life;

    y The Law of an Excluded Alternative;

    y Identify a major time-wasters;

    y Practical ways to overcome and avoid them if possible.

  • 8/6/2019 c Sharp by Nikhil

    32/40

    C Sharp by NIKHIL

    32

    Interfaces

    Interfaces

    An Interface is a reference type and it contains only abstract members.

    Interface's members can be Events, Methods, Properties and Indexers. But the

    interface contains only declaration for its members. Any implementation must be

    placed in class that realizes them. The interface can't contain constants, data fields,

    constructors, destructors and static members. All the member declarations inside

    interface are implicitly public.

    Defining an Interface:

    Let us look at a simple example for c# interfaces. In this example interface

    declares base functionality of node object.

    interface INode

    {

    string Text

    {

    get;

    set;

    }

    object Tag

    {

    get;set;

    }

    int Height

    {

    get;

  • 8/6/2019 c Sharp by Nikhil

    33/40

    C Sharp by NIKHIL

    33

    set;

    }

    int Width

    {get;

    set;

    }

    float CalculateArea();

    }

    The above INode interface has declared a few abstract properties and function

    which should be implemented by the derived classes.

    Sample for Deriving a class using a C# .Net interface

    public class Node : INode

    {

    public Node()

    {}

    public string Text

    {

    get

    {

    return m_text;

    }

    set

    {

    m_text = value;

    }

    }

    private string m_text;

    public object Tag{

    get

    {

    return m_tag;

    }

  • 8/6/2019 c Sharp by Nikhil

    34/40

    C Sharp by NIKHIL

    34

    set

    {

    m_tag = value;

    }}

    private object m_tag = null;

    public int Height

    {

    get

    {

    return m_height;

    }

    set{

    m_height = value;

    }

    }

    private int m_height = 0;

    public int Width

    {

    get

    {

    return m_width;

    }

    set

    {

    m_width = value;

    }

    }

    private int m_width = 0;

    public float CalculateArea()

    {

    if((m_width

  • 8/6/2019 c Sharp by Nikhil

    35/40

    C Sharp by NIKHIL

    35

    Now the above code has created a c# class Node that inherits from INode c#

    interface and implement all its members. A very important point to be

    remembered about c# interfaces is, if some interface is inherited, the program

    must implement all its declared members. Otherwise the c# compiler throws an

    error.

    The above code was a simple example of c# interface usage. Now this has to

    be followed with some advanced details of interface building in C# .Net. The

    previous example used only names of methods or properties that have the same

    names as in interface. But there is another alternative method for writing the

    implementation for the members in class. It uses full method or property name

    .

    Multiple Inheritance using C# interfaces:

    Next feature that obviously needs to be explained is multiple inheritance using

    c# interfaces. This can be done using child class that inherits from any number

    of c# interfaces. The inheritance can also happen with a combination of a C#.Net class and c# interfaces. Now let us see a small piece of code that

    demonstrate us multiple inheritance using only interfaces as parent data types

    class ClonableNode : INode,ICloneable

    {

    public object Clone()

    {

    return null;

    }

    // INode members

    }

    The above example created a class ClonableNode. It implements all the

    functionality of INode interface in the same way as it was done in Node class.

    Also it realizes Clone method only one item of IClonable interface of .NET

    library.

    is Operator for C# .Net interfaces -

    At last a new C# operator that can be used to define that class should be

    explained. It is the is operator. Look at the following piece of code:

    if(nodeC is INode)

  • 8/6/2019 c Sharp by Nikhil

    36/40

    C Sharp by NIKHIL

    36

    Console.WriteLine("nodeC is object of INode type");

    else

    Console.WriteLine("nodeC isn't object of INode type");

    In example nodeC object was created as ClonableNode type, but when we run

    program "if operator" returns true. It means that nodeC also is of INode type.

    Delegates in C#

    Delegates in C# .Net:

    If we look at C++ there is a feature called callback function.

    This feature uses Pointers to Functions to pass them as parameters to other

    functions. Delegate is a similar feature but it is more type safe, which stands as a

    stark contrast with C++ function pointers. A delegate can hold reference/s to one

    more more functions and invoke them as and when needed.

    A delegate needs the method's name and its parameters (input and output

    variables) when we create a delegate. But delegate is not a standalone

    construction. it's a class. Any delegate is inherited from base delegate class of

    .NET class library when it is declared. This can be from either of the twoclasses from System.Delegate or System. MulticastDelegate.

    If the delegate contains a return type of void, then it is automatically aliased tothe type of System.MulticastDelegate. This can support multiple functions

    with a += operator. If the delegate contains a non-void return type then it isaliased to System. Delegate class and it cannot support multiple methods.

    Let us have alookat the following sample code.

    class Figure

    {

    public Figure(float a, float b, float c)

    {

    m_xPos = a;

    m_yPos = b;

  • 8/6/2019 c Sharp by Nikhil

    37/40

    C Sharp by NIKHIL

    37

    m_zPos = c;

    }

    public void InvertX()

    {m_xPos = - m_xPos;

    }

    public void InvertY()

    {

    m_yPos = - m_yPos;

    }

    public void InvertZ()

    {

    m_zPos = - m_zPos;

    }

    private float m_xPos = 0;

    private float m_yPos = 0;

    private float m_zPos = 0;

    }

    Now, we have a class named Figure and it has three private fields that use to

    store position and three methods to invert this position by every axis. In main

    class we declare delegate as follows:

    public delegate void FigureDelegate();

    And now in the main function we should use it like this:

    Figure figure = new Figure(10,20,30);

    FigureDelegate fx = new FigureDelegate(figure.InvertX);

    FigureDelegate fy = new FigureDelegate(figure.InvertY);

    FigureDelegate fz = new FigureDelegate(figure.InvertZ);

    MulticastDelegate f_del = fx+fy+fz;

    In this example we create three delegates of FigureDelegate type and attach to

    these elements our three methods from Figure class. Now every delegate keeps

    the address of the attached function. The last line of code is very interesting,here we create a delegate of base type (MulticastDelegate) and attach three of

    our already created delegates. As all our methods are of void return type they

    are automatically of type MutlticastDelegate and a MulticastDelegate can

    support multiple methods invocation also. Hence we can write

  • 8/6/2019 c Sharp by Nikhil

    38/40

    C Sharp by NIKHIL

    38

    Figure figure = new Figure(10,20,30);

    FigureDelegate fMulti = new FigureDelegate(figure.InvertX);

    fMulti += new FigureDelegate(figure.InvertY);fMulti();

    Events in C# .Net

    Events in C# .Net:

    Delegate usefulness does not just lie in the fact that it can hold the

    references to functions but in the fact that it can define and use functionnames at runtime and not at compile time.

    A large goal of design delegates is their applicability in events model of .Net.

    Events are the actions of the system on user manipulations (e.g. mouse clicks,

    key press, timer etc.) or any event triggered by the program. To understand the

    usage of delegates for event model, the previous examples are used here. We

    should add to our Figure class next things:

    public delegate void FigureHandler(string msg);

    public static event FigureHandler Inverted;

    public void InvertZ()

    {

    m_zPos = - m_zPos;

    Inverted("inverted by z-axis");

    }

    Now we have a delegate declared and event that uses this delegate's type.

    In every function we should call our event. The next code snippet should

    explain it clearly

    static void Main(string[] args){

    Figure figure = new Figure(10,20,30);

    Figure.Inverted+=new Test.Figure.FigureHandler(OnFigureInverted);

    figure.InvertX();

  • 8/6/2019 c Sharp by Nikhil

    39/40

    C Sharp by NIKHIL

    39

    figure.InvertZ();

    }

    private static void OnFigureInverted(string msg)

    {

    Console.WriteLine("Figure was {0}",msg);

    }

    So, in the main function we should create an object of figure class and

    attach event handler to the method OnFigureInverted. And when we callany of invert methods the event is fired and it calls our event handler. The

    application will print the following string into the console: Figure wasinverted by x-axis Figure was inverted by z-axis .

  • 8/6/2019 c Sharp by Nikhil

    40/40

    C Sharp by NIKHIL