.NetFramework Concepts part-4

  Object Oriented Programming(OOP)

The programming in which data is logically represented in the form of a class and physically represented in the form an object is called as object oriented programming (OOP). OOP has the following important features.

Class :

In OOP languages it is must to create a class for representing data. Class contains variables for storing data and functions to specify various operations that can be performed on data. Class will not occupy any memory space and hence it is only logical representation of data.

Data Encapsulation : 

Within a class variables are used for storing data and functions to specify various operations that can be performed on data. This process of wrapping up of data and functions that operate on data as a single unit is called as data encapsulation.

Data Abstraction : 

Within a class if a member is declared as private, then that member can not be accessed from out side the class. I.e. that member is hidden from rest of the program. This process of hiding the details of a class from rest of the program is called as data abstraction. Advantage of data abstraction is security.

Object And Instance : 

Class will not occupy any memory space. Hence to work with the data represented by the class you must create a variable for the class, which is called as an object. When an object is created by using the keyword new, then memory will be allocated for the class in heap memory area, which is called as an instance and its starting address will be stored in the object in stack memory area.

When an object is created without the keyword new, then memory will not be allocated in heap I.e. instance will not be created and object in the stack contains the value null. When an object contains null, then it is not possible to access the members of the class using that object.

Student S1=new Student();

Student S2;

Inheritance : 

Creating a new class from an existing class is called as inheritance. When a new class requires same members as an existing class, then instead of recreating those members the new class can be created from existing class, which is called as inheritance. Advantage of inheritance is reusability of the code. During inheritance, the class that is inherited is called as base class and the class that does the inheritance is called as derived class.

Polymorphism : 

Polymorphism means having more than one form. Polymorphism can be achieved with the help of overloading and overriding concepts. Polymorphism is classified into compile time polymorphism and runtime polymorphism.

Access Modifiers

An access modifier is a keyword of the language that is used to specify the access level of members of a class. C#.net supports the following access modifiers.

Public: 

When Members of a class are declared as public, then they can be accessed

Within the class in which they are declared.

Within the derived classes of that class available within the same assembly.

Outside the class within the same assembly.

Within the derived classes of that class available outside the assembly.

Outside the class outside the assembly.

Internal:

When Members of a class are declared as internal, then they can be accessed

Within the class in which they are declared.

Within the derived classes of that class available within the same assembly.

Outside the class within the same assembly.

Protected: 

When Members of a class are declared as protected, then they can be accessed

Within the class in which they are declared.

Within the derived classes of that class available within the same assembly.

Within the derived classes of that class available outside the assembly.

Protected internal: 

When Members of a class are declared as protected internal, then they can be accessed

Within the class in which they are declared.

Within the derived classes of that class available within the same assembly.

Outside the class within the same assembly.

Within the derived classes of that class available outside the assembly.

Private: 

Private members of a class are completely restricted and are accessible only within the class in which they are declared.

Garbage Collector: 

Garbage Collector is available in CLR of .net framework and it is responsible for complete memory management for the .net applications. Allocating memory for the objects and de allocation of memory when their life time is completed is the responsibility of garbage collector. Various steps performed by garbage collector when it was invoked are as follows.

Suspends all the threads in .net application and it will run on a separate thread.

It draws a graph of all reachable objects. An object that contains a reference to heap memory area is called as reachable object and the object that contains null is called as unreachable object. All the objects that are not in the graph will be unreachable objects.

All unreachable objects with a destructor will be added to a queue called Freachable queue.

All unreachable objects without a destructor are destroyed and all reachable objects will be moved down the heap to make free memory available at the top of the heap. While moving reachable objects down the heap, garbage collector will update the objects to refer to new memory location.

Resumes the threads of the .net application.

Destroys all unreachable objects with a destructor available in freachable queue.

Memory Management By Garbage Collector

Garbage collector maintains a pointer with the name “NextObjPtr” that initially points to the base address of heap memory area and when memory is allocated for an object, then this pointer will move to next byte of the memory allocated for the object. Hence this pointer always contains the address of a memory location that is to be allocated for next new object created. Prior to allocating memory, it will add required bytes for the new object to address available in NextObjPtr. If the address obtained is within the area of heap, then memory is allocated and if the obtained address is beyond the heap memory area then it means that heap memory area is full and it is the time to perform garbage collection.

All the objects in heap memory area up to first garbage collection will be treated as generation0 and after garbage collection; the new objects created in heap will be treated as generation1. Main purpose of maintaining generations is to make the garbage collection fast. The time taken to perform garbage collection of a particular generation will be very less when compared to the garbage collection of entire heap.

If again heap memory becomes full, then garbage collection will be done for generation0. If sufficient memory is available after garbage collection on generation0, then memory is allocated for new object without performing garbage collection on generation1. Otherwise garbage collection will be performed on generation1 and then memory allocated for the new object. Now onwards the new objects created will be treated as generation2.

When heap memory again becomes full, then garbage collection is performed on generation0 and generation1 and all remaining reachable objects in generation0 and generation1 will be treated as generation0 and all objects in generation2 will be now moved to generation1 and newly created objects will be now treated as generation2 and the same will be continued. In .net framework 2.0, garbage collector algorithm contains only three generations.

Windows Services

A Windows service is a windows application without any GUI. It runs automatically when windows operating system was started and will be automatically shutdown when windows operating system was shutdown. Anti virus programs are examples for windows services. They run in the background of windows without any GUI and whenever a file containing virus was copied to the system, it will find it and remove the virus. In the same way when you connect a pen drive to the system then it will be automatically detected and a drive is created for it and all this is done by a windows service.

To create your own windows service, use “windows service” template in new project dialog box. A windows service is inherited from “ServiceBase” class and is available in the namespace “System.ServiceProcess”. “ServiceBase” class contains virtual methods “OnStart()”,”OnStop()”,”OnPause()”,”OnContinue()” and “OnShutdown()” that can be overridden in your windows service to write the code to be executed when the service was started, stopped, paused, continued and shutdown respectively.

Example : The following example creates a windows service that detect the changes made to a folder with the name “Test” in D drive and writes an entry to a file “MyService.Txt” whenever a change was made to the file. To identify the changes made to a folder in the operating system, “FileSystemWatcher” component available in components tab of the toolbox is used.

1. Create a new project by selecting “Windows Service” template in the new project dialog box and by specifying the name as “MyService” and in the solution explorer rename the file “Service1.cs” to “MyService.Cs”.

2. Open the properties of windows service and set the “DisplayName” property to “MyService”.

3. Place a “filesystemwatcher” on to the windows service and set following properties to it.

Name : FSW

EnableRaisingEvents: true

Filter : *.*

IncludeSubDirectories: true

Path : D:\Test

4. Within the code add the reference tp System.IO namespace and then create a filestream and streamwriter in the class of the windows service as follows.

FileStream Fs;

StreamWriter Sw;

5. Write the following code in the method “OnStart()” by overriding it.

protected override void OnStart(string[] args)

{

Fs = new FileStream(@"D:\MyService.Txt", FileMode.OpenOrCreate,FileAccess.Write);

Sw = new StreamWriter(Fs);

Sw.BaseStream.Seek(0, SeekOrigin.End);

Sw.WriteLine("MyService Started At " + DateTime.Now.ToString());

Sw.Flush();

}

6. Write the following code in the method “OnStop()” by overriding it.

protected override void OnStop()

{

Sw.BaseStream.Seek(0, SeekOrigin.End);

Sw.WriteLine("MyService Stopped At " + DateTime.Now.ToString());

Sw.Flush();

Sw.Close();

Fs.Close();

}

7. Write the following code in “OnPause()” and “OnContinue()” methods by overriding them so that filesystemwatcher will not raise any event when service was paused and again raises events when continued.

       protected override void OnPause()

        {

            Fsw.EnableRaisingEvents = false;

        }

        protected override void OnContinue()

        {

            Fsw.EnableRaisingEvents = true;

        }

8. Write the following code in “Created” event of the filesystemwatcher that will be raised whenever a new file/folder was created in the given path.

private void Fsw_Created(object sender, FileSystemEventArgs e)

{

Sw.BaseStream.Seek(0, SeekOrigin.End);

Sw.WriteLine("A New File/Folder " + e.FullPath + " Was Created At " +

DateTime.Now.ToString());

Sw.Flush();

}

9. Write the following code in “Renamed” event of the filesystemwatcher that will be raised whenever a file/folder was renamed in the given path.

private void Fsw_Renamed(object sender, RenamedEventArgs e)

{

Sw.BaseStream.Seek(0, SeekOrigin.End);

Sw.WriteLine("A File/Folder " + e.OldFullPath + " Was Renamed as " +

e.FullPath + " At " + DateTime.Now.ToString());

Sw.Flush();

}

10. Write the following code in “Deleted” event of the filesystemwatcher that will be raised whenever a file/folder was Deleted in the given path.

private void Fsw_Deleted(object sender, FileSystemEventArgs e)

{

Sw.BaseStream.Seek(0, SeekOrigin.End);

Sw.WriteLine("A File/Folder " + e.FullPath + " Was Deleted At " +

DateTime.Now.ToString());

Sw.Flush();

}

11. Add installer to the project by right clicking on design of the windows service and choosing “Add Installer”. To install a windows service, installer is required. This will add two components to the windows service, “Service Installer” and “Service process Installer”. “Service Installer” is used to install the windows service and write any entries to windows registry and “Service Process Installer” is used to start a particular process in windows service.

12. for the “Service Installer” set following properties.

DisplayName: MyService

ServiceName: MyService

StartType: Automatic

13. for the “Service Process Installer” set the property “Account” to “LocalSystem” to indicate that this service is available for every user in the local system.

14. change the solution configuration to “Release” and build the solution using the shortcut “Ctrl+Shift+B” to generate an exe file for the project.

Installing Windows Service : To install windows service, use the command line tool “Installutil.exe” that has the following syntax.

InstallUtil  /i  pathofexefile

When you want to uninstall the windows service, use installutil command line tool with the following syntax.

InstallUtil  /u  pathofexefile.

Object Comparison

In .net when you want to compare two objects for equality, then objects may be value equivalent or reference equivalent. Two objects are said to be value equivalent, if and only if they both are of same type and contain same values. To compare two objects for value equivalent, Equals() method of object class is used. By default every class in .net is inherited from object class. Equals() method is a virtual method in object class and you have to override that method in your class to use it for value equivalent comparison of objects of your class. When you want to compare two objects obj1 and obj2 for value equivalent, then syntax will be as follows.

                                                Obj1.Equals(Obj2)

Two objects are said to be reference equivalent, if and only if they both are of same type and contain same reference. When two objects are reference equivalent, then they are automatically reference equivalent. To compare two objects for reference equivalent, ReferenceEquals() method of object class is used. ReferenceEquals() method is a static method in object class. To compare two objects obj1 and obj2 for reference equivalent, syntax is as follows.

                                    Object.ReferenceEquals(obj1,obj2)

Example : The following example creates a class Test that contains a float field and overloads the operator > and < used for comparison of objects of the class Test.

Write a program to illustrate Object comparision in C#.NET?

namespace Inheritance

{

    class Test2

    {

        float F;

        public void Read()

        {

            Console.Write("Enter Value For F : ");

            F = float.Parse(Console.ReadLine());

        }

        public override bool Equals(object obj)

        {

            Test2 T = (Test2)obj;

            if (this.F == T.F)

                return true;

            else

                return false;

        }

        public override int GetHashCode()

        {

            return base.GetHashCode();

        }

        public static bool operator ==(Test2 T1, Test2 T2)

        {

            if (object.ReferenceEquals(T1, T2))

            {

                return true;

            }

            if (T1.Equals(T2))

            {

                return true;

            }

            return false;

        }

        public static bool operator !=(Test2 T1, Test2 T2)

        {

            return !(T1 == T2);

        }

    }

    class GTOL

    {

        static void Main()

        {

            Test2 T1 = new Test2();

            Test2 T2 = new Test2();

            Test2 T3 = T2;

            T1.Read();

            T2.Read();

            if (T1 == T2)

                Console.WriteLine("T1 And T2 Are Equal");

            else

                Console.WriteLine("T1 And T2 Are Not Equal");

            if (T2 == T3)

                Console.WriteLine("T2 And T3 Are Equal");

        }

    }

}

Creating Functions In C#

A function is a self contained block of statements that perform a special task. When we have the code to be repeated at different locations in a program, then that code will be created as a function and will be called wherever that code is needed. Syntax for creating a function in C# is same as creating functions in C and C++ and is as follows.

[Access Modifier] Returntype FunctionName([Parameters])

{          

  ---       

}

Same as in C language when a function doesn’t return any value, the return type will be specified as void.

Example : The following example creates a function that calculates sum of given five integers.

namespace Language

{

    class FunctionSum

    {

        public static int Sum(int A, int B, int C, int D, int E)

        {

            return A + B + C + D + E;

        }

        static void Main()

        {

            Console.WriteLine(Sum(10, 20, 30, 40, 50));

            Console.WriteLine(Sum(12, 34, 55, 63, 26));

            Console.WriteLine(Sum(9, 19, 29, 39, 49));

        }

    }

}


Example : The following example creates a function that accepts an integer and returns its factorial.

Write a program to find factorial of given number in C#.NET?

namespace Language

{

    class FunctionFactorial

    {

        public static int Fact(int n)

        {

            int F = 1;

            for (int i = 1; i <= n; i++)

            {

                F *= i;

            }

            return F;

        }

        static void Main()

        {

            Console.WriteLine(Fact(5));

            Console.WriteLine(Fact(7));

            Console.WriteLine(Fact(3));

        }

    }

}

Default Arguments

C++ supports a concept called default arguments, which is provided in VB.net as optional parameters. With default parameters in a function, you can call a function with variable number of arguments. For example, if you create a function in C++ as follows,

int Sum(int A, int B, int C=0, int D=0, int E=0)

{

            return A+B+C+D+E;

}

Then from main this function can be called with only two arguments or three arguments or four arguments or five arguments as follows.

S=Sum(10,20)

S=Sum(10,20,30)

S=Sum(10,20,30,40)

S=Sum(10,20,30,40,50)

In this case, the parameters C, D and E are initialized to 0 in function declaration and these are called as default arguments and while calling the function, passing arguments these parameters is optional. When you are not passing arguments to these parameters, then default value 0 will be taken and code is executed and when you are passing an argument to these parameters then that argument will overwrite the default value 0.

This concept of default arguments in C++ or optional parameters in vb.net are not supported in C#.

Param Array Parameters

When you want to allow the user to call a function with any number of arguments of same data type, then parameter must be declared as an array. To declare a parameter as an array, parameter must be declared using the keyword params and in this case the parameter is called as param array parameter. There are following restrictions on param array parameters.

A function can have only one param array parameter.

Param array parameter must be last parameter in parameter list.

Param array parameter must not be ref or out parameter.

Example : The following example creates a function that can accept any number of integers and returns their sum.

namespace Language

{

    class FunctionSumParamArray

    {

        public static int Sum(params int[] A)

        {

            int S = 0;

            foreach (int n in A)

            {

                S += n;

            }

            return S;

        }

        static void Main()

        {

            Console.WriteLine(Sum(10, 20, 30));

            Console.WriteLine(Sum(10, 20, 30, 40, 50));

            Console.WriteLine(Sum(10, 20, 30, 40, 50, 60, 70, 80, 90, 100));

        }

    }

}

Reference Parameters

Function calling is of two types, call by value and call by reference. By default function call in C# is call by value where any changes made to the parameters within the function will not reflect in arguments passed to them. The process of making the changes in parameters in function reflect in the arguments passed to them is called as call by reference. To implement call by reference in C#, parameters must be declared as reference parameters and to declare a parameter as reference parameter, precede the parameter declaration with the keyword ref. when a parameter is declared with the keyword ref, then the arguments must also be preceded with the keyword ref while calling the function.

Example : The following example creates a function with the name swap that swaps two integers using reference parameters.

Write a program to swap two numbers with C#.NET

namespace Language

{

    class RefSwap

    {

        public static void Swap(ref int x, ref int y)

        {

            int T = x;

            x = y;

            y = T;

        }

        static void Main()

        {

            int A = 10, B = 20;

            Console.WriteLine("Values Before Swap A = {0} And B = {1}", A, B);

            Swap(ref A, ref B);

            Console.WriteLine("Values After Swap A = {0} And B = {1}", A, B);

        }

    }

}

Implementation of call by reference in C# is similar to implementing call by reference in C++ using reference parameters i.e. when the function is called, the parameters will be created as aliases for the arguments passed to them and hence any changes made to parameters will reflect in arguments as they both are referring to same memory address.

Pointers in C#.NET

Pointer is a variable that can store address of another variable of same data type. Actually .net doesn’t support pointers. Because there is no security for data with pointers as there is direct access to data with the help of address of the variable. But there are some situations where it is compulsory to use pointers. For these situations pointers are supported in C#.net. When code was written in C# using pointers, then that code will not run under the control of code manager and hence it is called unmanaged code or unsafe code. While writing unsafe code in C#, that code must be marked as unsafe and for this unsafe keyword is used. To make a method as unsafe, syntax is as follows.

            [Access Modifier] unsafe returntype MethodName([Parameters])

            {

                        ---

            }

To Mark only a set of statements in a method as unsafe, but not entire method as unsafe, the following syntax is used

            Unsafe

            {

                        ---

            }

By default unsafe code compilation will not be enabled for the project. To enable unsafe code compilation, open properties of the project by right clicking on project in solution explorer and then choosing properties. Within project properties in Build Tab check the check box Allow Unsafe Code and close properties.

Pointer Declaration

Syntax : DataType* Var;

In C language to declare a variable as pointer, variable must be prefixed with *. But in C# data type will be suffixed with * to declare a variable as pointer.


Pointer Operators

&         -           AddressOf Operator, used to get address of a variable.

*           -           ValueAtAddress Operator, used to get value at given address.


Example : The following example creates a pointer that stores address of a variable and prints the address and value of that variable using pointer.

namespace Language

{

    class Pointers

    {

        unsafe static void Main()

        {

            int A = 10;

            int* P = &A;

            Console.WriteLine("Address Of A Is {0}", (int)P);

            Console.WriteLine("Value Of A Is {0}", *P);

        }

    }

}

Example : The following example creates a function swap that swaps two integers using pointers.

namespace Language

{

    class PointersSwap

    {

        public unsafe static void Swap(int* x, int* y)

        {

            int T = *x;

            *x = *y;

            *y = T;

        }

        static void Main()

        {

            int A = 10, B = 20;

            Console.WriteLine("Values Before Swap A = {0} And B = {1}", A, B);

            unsafe

            {

                Swap(&A, &B);

            }

            Console.WriteLine("Values After Swap A = {0} And B = {1}", A, B);

        }

    }

}

Out Parameters

Out parameters are same as ref parameters and any changes made to out parameters within a function will reflect in arguments passed to them. But the difference is to use an out parameter within a function, it must be initialized first and a reference parameter can be used within a function without initialization.

The main purpose of call by reference is to make a function return more than one value. By default a function can return only one value. But there may be a situation where you may want to return more than one value from a function. In that situation call by reference has to be used.

Example : The following example creates a function calculate that calculates and returns both total and average of given three integers.

namespace Language

{

    class OutParams

    {

        public static int Calculate(int A, int B, int C, out float Avg)

        {

            int T = A + B + C;

            Avg = T / 3.0F;

            return T;

        }

        static void Main()

        {

            int M1, M2, M3, Total;

            float Aveg = 0;

            Console.WriteLine("Enter Marks In Three Subjects");

            M1 = int.Parse(Console.ReadLine());

            M2 = int.Parse(Console.ReadLine());

            M3 = int.Parse(Console.ReadLine());

            Total = Calculate(M1, M2, M3, out Aveg);

            Console.WriteLine("Total : {0}", Total);

            Console.WriteLine("Aveg  : {0}", Aveg);

        }

    }

}

                                                    For Part3 Click here

                                  For Part5 Click here


Thanks for visiting this blog. How is the content?. Your comment is great gift to my work. Cheers.







No comments:

Post a Comment