• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C# » CSharp

C# Windows Application

C# libraries

Advanced Csharp

C# Oops

Introduction

DotNet

CSharp

Asp.Net Execution Model

By Dinesh Thakur

When the client requests a Web page for the first time, the following set of events take place:

 

1. The client browser issues· a GET HTTP request to the server.

2. The ASP.NET parser interprets the source code.

3. If the code was not already compiled into a dynamic-link library (DLL), ASP.NET invokes the compiler.

4. Runtime loads and executes the Microsoft intermediate language (MSIL) code.

                                 ASP.NET EXECUTION MODEL . 

When the user requests the same Web page for the second time, the following set of events take place:

1. The client browser issues a GET HTTP request to the server.

2. Runtime loads and immediately executes the MSIL code that was already compiled during the user’s first access attempt.

How to Create a Web Forms in C#

By Dinesh Thakur

Web Forms consist of a combination of HTML, code, and controls that execute on a Web server that i’s running Microsoft Internet Information Services (lIS). Web Forms display a UI by generating HTML that is sent to the browser, while the supporting code and controls that run the UI stay on the Web server. This split between client-side interface and server-side code is a crucial difference between Web Forms and traditional Web pages. While a traditional Web page requires all of the code to be sent to ahd be processed at the Browser, Web Forms need to send only the interface controls to the browser ,and the page processing is kept on the server. This UI/code split increases the range of supported browsers while increasing the security and functionality of the Web page.

Web Forms are commonly referred to as ASP.NET pages or ASPX pages. Web Forms have an .aspx extension and work as the containers for the text and controls that you want to display on the browser.

ASP.NET (.aspx) pages and Active Server Pages (ASP) can coexist on the same server.

The file extension determines whether ASP or ASP.NET processes it.

Web Forms are often comprised of two separate files: the .aspx file contains the UI for the Web Form, while the .aspx.vb or .aspx.cs file, which is called a code-behind page, contains the supporting code.

When you create a new project in Visual Studio .NET, a default Web Form named WebForm1.aspx is automatically included in the project .

 

To create a new ASP.NET Web Application-project and a default Web Form you have to follow the following steps:

 

1. In Visual Studio .NET, on the Start Page, click New Project.

2. In the New Project dialog box, click ASP.NET Web Application, type the project name in the Location field, and then click OK.

                                In the New Project dialog box, click ASP.NET Web Application, type the project name in the Location field, and then click OK.

Visual Studio.NET creates a new Web application and a default Web Form that is, name WebForml.aspx. If you are expanding an existing project, you can use Solution Explorer to quickly add additional Web Forms.

                                Visual Studio.NET creates a new Web application and a default Web Form that is, name WebForml.aspx.

3. Now add the Button control from the toolbox:

                               add the Button control from the toolbox

4. Now right click on the button control and select the properties.

                               Now right click on the button control and select the properties

5. Now change the text property of the button from “Button” to “Message” or whatever you like .

 

                               the text property of the button

This will change the caption of button control from “Button” to “Message”.

 

                              change the caption of button control

6. Double click on the button control and write the following code in the Button 1_Click event.

                              Button 1_Click event

7. After saving the project you must build the project.

8. Now right click on the web form and select ”View in Browser”.

                              View in Browser

9. The output will appear looks like following figure.

                              

10. Now click on the Message button. you will see the following result.

                              

The steps to add additional Web Forms to a Web Application project:

1.In the Solution Explorer window, right-click the project name, point to Add, and then click Add Web Form. The Add New Item – Project Name dialog box opens.

2. In the Add New Item – Project Name dialog box, change the name of the Web Form, . and then click Open.

A new Web Form will be created and added to the project.

Type of Windows Forms controls

By Dinesh Thakur

A Windows Forms control is a class that derives directly or indirectly from System. Windows. Forms. Control. The following list describes common scenarios for developing Windows Forms controls.

The base class for Windows Forms controls, System.Windows.Forms.Control, provides the plumbing required for visual display in client-side Windows applications. Control provides a window handle, handles message routing, and provides mouse and keyboard events as well as many other user interface events. It provides advanced layout and has properties .specific to visual display, such as ForeColor, BackColor, Height, Width, and many others. Additionally, it provides security, threading support, and interoperability with ActiveX controls. Because so much of the infrastructure is provided by the base class,· it is relatively easy to develop your own Windows Forms. controls.

The Windows Forms controls are listed here according to general function you can find all of these controls in the ToolBox.

                 A Windows Forms control is a class that derives directly or indirectly from System. Windows. Forms. Control.

                  A Windows Forms control is a class that derives directly or indirectly from System. Windows. Forms. Control.

Explaining all of the controls present in visual studio is impossible within the scope of this book, but some· most important controls are described in the next few sections.

Button

The Windows Forms Button control allows the user to click it to perform an action. The Button control· can display both text and images. When the button is clicked, it looks as if it is being pushed in and released.

                              

Whenever the user clicks a button, the Click event handler is invoked. You place code in the Click event handler to perform any action you choose.

The text displayed on the button is contained in the Text property. ·If your text exceeds the width of the button, it will wrap to the next line. However, it will be clipped if the control cannot accommodate its overall height. The Text property can contain all. access key, which allows a user to “click” the control by pressing the ALT key with the access key. The appearance of the text is controlled by the Font property and the TextAlign property. The Button control can also display images using the Image and ImageList properties. The most basic use of a Windows Forms Button control is to run some code when the button is clicked.

Clicking a Button control also generates a number of other events, such as the MouseEnter, MouseDown, and MouseUp events. If you intend to attach event handlers for these related events, be sure that their actions do not conflict. For example, if clicking the button clears information that the user has typed in a text box, pausing the mouse pointer over the button should not display a tool tip with that now-nonexistent information.

If the user attempts to double-click the Button contr91, each click will be processed separately; that is, the control does not support the double-click event.

 

How to respond to a button click

 

To assign an action on the button control write the following code in the button’s Click event handler or double click on the button in design mode it will directly transfer you to click event handler. The code written’ in handler will display a message box which will show Button1 was clicked” message.

 

Example:

 

private void button1-click(object sender, System.EventArgs e),

{

MessageBox.show(“button1 was clicked”);

}

 

Check Box

 

The Windows Forms CheckBox control indicates whether a particular condition is on or off. It is commonly used to present a Yes/No or True/False selection to the user. You can use, check box controls in groups to display multiple choices from which the user can select one or more

                           The Windows Forms CheckBox control indicates whether a particular condition is on or off.

The check box control is similar to the radio button control in that each is used to indicate a selection that is made by the user. They differ in that only one radio button in a group can be selected at a time. With the check box control, however, any number of check ‘boxes may be selected.’

A check box may be connected to elements in a database using simple data, binding.

Multiple check boxes may be grouped using the GroupBox control This is useful for visual appearance and also for user interface design, since grouped controls can be moved around together on the form designer.

The CheckBox control has two important properties, Checked and CheckState. The

Checked property returns either true or false. The CheckState property returns either

CheckState Checked or CheckState.Unchecke1d or, if the ThreeState property is set to true, CheckState may also return CheckState in determinate. In the indeterminate state, the box is displayed with a dimmed appearance to indicate the option is unavailable.

Whenever a user clicks a Windows Forms Check Box control, the Click event occurs. You can program your application to perform some action depending- upon the state of the check box.

 

How to respond to CheckBox clicks

 

To assign an action on the CheckBox control write the following code in the CheckBox’s

Click event handler. The code written in handler of checkBox control will change Text property each time the control is clicked, indicating a checked or unchecked state.

 

private void checkBox1_click(object sender, System. EventArgs e)

{

if (checkBox1.checked)

{

checkBox1. Text + = “checked”;

}

else

{

checkBox1.Text += ” Unchecked’

}

}

 

Label

Windows Forms .Label controls are used to display text or images that cannot be edited by the user. They are used to identify objects on a form – to provide a description of what a certain control will do if clicked, for example, or to display information in response to a runtime event or process in your application. For example, you can use labels to add descriptive captions to text boxes, list boxes, combo boxes, and so on. You can also write code that changes the text displayed by a label in response to events at run time. For example, if your application takes a few minutes to process a change, you can display a processing-status message in a label.

                               Windows Forms .Label controls are used to display text or images that cannot be edited by the user.

The caption displayed in the label is contained in the Text property. The Alignment property allows you to set the alignment of the text within the label.

TextBox

Windows· Forms text boxes are used· to get input from the user or to display text. The textBox control is generally used for editable text, although it can also be made read-only. Text boxes can display multiple lines, wrap text to the size of the· control, and add basic formatting. The TextBox control provides a single format style for text displayed or entered into the control. To display multiple types of formatte4 text, use the RichTextBox control.

                                Windows• Forms text boxes are used• to get input from the user or to display text.

The text displayed by the control is contained in the Text property. By default,’ you enter up to 2048 characters in a text box. If you set the Multiline property to true, you enter up to 32 KB of text. The Text property can be set at( design time with the Properties window, at run time in code, or by user input at run time. The current contents of a text be! can be retrieved at run time by reading the Text property ..

The code below sets text in the control at run time. The InitializeMyCoutrol procedure will not execute. automatically it must be called

 

private void InitializeMycontrol()

{

I I Put some text into the contro1 first .

textBox1.Text = “Thi5 . is a TextBox control,,”;

}

 

To create a password text box

 

A password box is a Windows Forms text box that displays placeholder’ characters a user types a string.

1. Set the PasswordChar property of the TextBox control to a specific character. The PasswordChar. property specifies the character displayed in the text box. example, if you want asterisks displayed in the password box, specify * for the PasswordChar property in the Properties window. Then, regardless of what character a user types in the text box, an asterisk is displayed.

2. (Optional) set the MaxLength property. The property determines how many characters can be typed in the text box. If the maximum length is exceeded, the system, emits beep and the text does not accept any more characters. Note that you may not wish to do this’ as the maximum length of a password may be of use to hackers who are trying to guess the password.

                                 

The code below initializes a text box that will accept a string up to 14 characters long and display asterisks in place of the string. The InitializeMyControl procedure will not execute automatically; it must be called.

 

private void InitializeMycontrol()

{

II Set to no text.

textBox1.Text = “”;

II The password character is an asterisk.

textBox1~passwordchar = ‘*’;

II The control’ will allow no more than 14 characters.

textBox1.MaxLength= 14;

}

 

ComboBox

The Windows Forms ComboBox control is used to display data in a drop-down combo Box. By default, the ComboBox control appears’ in two parts: the top part is a text box allows the user to type a list item. The second part is a list box: that displays a list of item from which the user can select one.

                                The Windows Forms ComboBox control is used to display data in a drop-down combo Box.

The Selectedlndex property returns an integer value that corresponds to the selected list item. You can programmatically change the-selected item by changjng the Selectedlndex value in code; the corresponding item in the list will appear in the text box portion of the combo box. If no item is selected, the Selectedlndex value is -1. If the-first item in the list is selected, then the Selectedlndex value is o. The Selectedltem property is similar to Selectedlndex, but returns the item itself, usually a string value. The Items.Countproperty reflects the number of items in the list, and the value of the Items.Count property is always one more than the largest possible Selectedlndex value because Selectedlndex Is zero-based.

How to Create a Windows Application in C#

By Dinesh Thakur

The foundation of most solutions that involve Windows Forms is the Windows Application project. Creating one is easy within the integrated development environment (IDE).

 

To Create a Windows Application project

• On the File menu, point to New, and then select Project.

                        To Create a Windows Application project

• In the left pane, choose visual C# project, and in the right pane, choose Windows Application.

                          In the left pane, choose visual C# project, and in the right pane, choose Windows Application.

Note: In the Name box, name the project something unique to indicate the application’s purpose. In the Location box, enter the directory in which you want to save your project, or click the Browse button to· navigate to it.

 

  • The Windows Forms Designer opens, showing Form1of the project you created.

                           Windows Forms Designer opens

WINDOWS FORMS

Forms Designer is a class, and when you display an instance of the form at run time, this class is the template used to create the windows form. The framework also allows you to inherit from existing forms to add functionality or modify existing behavior. When you add a form to your project, you can choose whether it inherits from the Form· class provided by the framework, or from a form you have previously created.

Windows form uses some controls, because they inherit from the Control class.

Within a Windows Forms project, the form is the primary vehicle for user interaction. By combining different sets of controls and writing code, you can obtain information from the user and respond to it, work with existing stores of data, and query and write back to the file system and registry on the user’s local computer.

Although the form can be created entirely in the Code Editor, it is easier to use the

Windows Forms Designer to create and modify forms.

 

Adding Button Control

 

To add any control to the Form Design

 

  • Open ToolBox from the View Menu. or you can press Ctrl + Alt + X as shortcut key.
  •                            Adding Button Control

Click on the Button option and Drag a single button from ToolBox to the middle of the form then it will shows as following figure with “button1” name on the form.

                                       Adding Button Control

  • To Change the name of Button open the properties after right click on the button control.
  •                                      • To Change the name of Button open the properties after right click on the button control.
  • Change the text property from button1 to “OK”
  •                                        
  •                                          Change the text property from button1 to “OK”

You can add more controls on the form which are available in Toolbox.

 

Adding windows Form to the project

 

Your windows application may need more than just a main form. The framework makes it easy to add dialog boxes, startup screens, and other supporting forms.

 

To add a windows Form that inherits from the Form class

 

  • In the Solution Explorer, right-click your project and choose ADD, the choose Windows Form.
  •                                        In the Solution Explorer, right-click your project and choose ADD, the choose Windows Form.   

To add a windows From that inherits from a previously created form class

 

  • In the Solution Explorer, right-click your project and choose Add, then choose Inherited Form.
  •                                         To add a windows Form that inherits from the Form class

Note: You can also add a Windows Form from the Project menu.

 

Resizing Windows Form

 

There are a number of ways to specify the size of your Windows Form, including manually within the Windows Forms Designer, using the Properties window, and in code.

 

To resize a form in the Windows Forms Designer

 

1. In the Windows Forms Designer, click the form to select it.

2. Click and drag one of the right sizing handle which appear on the border of the form.

The sizing handles look like small white boxes, and the mouse pointer turns into a double-headed arrow when you point at a handle.

                                             Windows Forms Designer

Note: Pressing the ARROW keys while holding down the SHIFT key allows you to resize the form more precisely.

 

To resize a form using the Properties window

 

• In the Properties window, click the Size property and enter values for the width and height, separated by a comma.

                                              To resize a form using the Properties window

Note : Expand the Size property to enter the Width and Height values individually .

Additionally, forms can be resized at run time. For example, if a form displays a bitmap, you may want to resize the form whenever the user selects a new bitmap.

 

To resize a form programmatically

 

• Define the size of a form at run time by setting the Size property of the form. The. following example shows the form size set to 100 by 100 pixels:

 

Form1.Size = new system.Drawing.Size(100, 100);

 

To change form width and height programmatically

 

• Once the Size object is defined, change either its Width or Height property. In the example below, the width of the form is set to 300 pixels from the left edge of the form, while the height stays constant .

 

Form1. width = 300;

 

• Change Width or Height by setting the Size property. As the following code snows, however, this approach is more cumbersome than simply setting Width or Height properties.

 

Form1.size = new Size(300, Form1.Size.Height);

Windows Application Developement in C#

By Dinesh Thakur

An important part of Visual Studio .NET is the ability to create Windows applications that run locally on users’ machines. Visual Studio .NET allows you to create the application and user interface using Windows Forms.

A Visual Studio Windows application is built around the .NET Framework, a rich set of classes that allows you to program sophisticated applications. You can create, Windows applications using any .NET programming language (Visual Basic, C#” Managed Extension for C++, and many others) and .NET debugging facilities.

Windows applications created with .NET classes afford you other benefits. You can access operating-system services and take advantage of other· benefits provided by your user’s computing environment. You can access data from database using ADO.NET. The GDI+ allows.’ you to do advanced drawing and painting within your windows forms.

Visual Studio .NET provides you an environment to create Windows applications .The advantage of using Visual Studio .NET is that it provides tools that make application development much faster, easier, and more reliable. These tools include:

• Visual designers for Windows Forms with drag-and-drop controls.

• Code-aware editors that include statement completion, syntax checking, and other

IntelliSense features.

• Integrated compilation and debugging.

• Project management facilities for creating and managing application files, including deployment locally, over an intranet or over the ·Internet.

If you have used Visual Studio before, these features will seem familiar; they are similar to features available in previous versions of Visual· Basic and Visual C++. Visual Studio .NET expands on these features to provide a superior environment for developing Windows applications.

WINDOWS APPLICATIONS DEVELOPMENT

Windows application development with Visual Studio can take many shapes. You can create Windows Forms and Windows service applications that leverage the power of the .NET Framework, or you can use ‘Visual C++ to create Win32 applications.

Windows Forms

A form is a bit of screen real estate, usually rectangular, that you can .use to present information to the user ad to accept input .from the user. Forms can be standard windows, multiple. document interface (MDI) windows, dialog boxes, or display surfaces for graphical routines. The easiest way to define the user interface for a form is to place controls on its surface. Forms are objects that expose properties which define their appearance, methods which define their behavior, and events which define their interaction with the user. By setting the properties of the form and writing code to respond to its events, you customize the object to meet the requirements of your application.

Windows Service Applications

Using Microsoft Visual Studio .NET or the Microsoft .NET Framework SDK, you can easily create services by creating an application that is installed as a service. This type of application is called a Windows service. With framework features, you can create services, install them, and start, stop, and otherwise control their behavior.

Win32 Projects

You can use the Project Wizard to create Win32 project types, including console applications, executable Windows applications, dynamic-link libraries, and static libraries.

Exception Handling in C#

By Dinesh Thakur

There are no exceptions in C arid in C++ one can get away from using them with error handling functions such as exit() and terminate(). In C# these functions are absent and we introduce exceptions which take their place. The exception handling in C#, and Java is quite similar.

When a program has a bug we can intercept it in the flow of execution by inserting an error handling statement. To catch a particular type of exception in· a piece of code, you have to first wrap it in a ‘try’ block and then specify a ‘catch’ block matching that type of exception. When an exception occurs in code within the ‘try’ block, the code execution moves to the end of the try box and looks for an. appropriate exception handler. For instance, the following piece of code demonstrates catching an exception specifically generated by division by zero:

try

{

int zero = 0;

res = (num/ zero);

}

catch (system.dvideByzeroException e)

.{

Console.writeLine(“Error: an attempt to divide by zero”);

}

You can specify multiple catch blocks (following .each other), to catch different types of exception. A complication results, .however, from the fact that exceptions form an object hierarchy, so a particular exception might match more than one catch box. What you have to do here is put catch boxes for the more specific exceptions before those for the more general exceptions. At most one catch box will be triggered by an exception, and this will be the first (and thus more specific) catch box reached.

For example, program, which does not, accesses the first element of an array. Then, during some array handling operations, if an access to array[O] is attempted, the’ OutOfRange exception is thrown. class OutOfRange is an exception class. ‘Allexception classes inherit from Exception class. Compiler, will give an error if the inheritance from, the Exception class is not made .

In the code that follows we throw an exception OutOfRange if i == 0 is true. The try statement is enclosing the part of the code where the exception is expected. If the exception occurs it is handled by the code inside the catch statement. The catch statement takes as an argument an instance of class System.Exception.

Exception Handling Program

 

using system;

class OutOfRange:Exception

{

}

class Demo

{

int n;

public int []array;

public Demo ( int n)

{

this.array = new int[n];

this.n = n;

}

public void show_element (int i)

{

try

{

if (i == 0) throw ( new OutOfRange());

catch (Exception e)

{

console.writeLine(“Exception :{0}”,e);

}

console.WriteLine (array [i]);

}

}

class Test

{

public static void Main()

{

Demo test = new Demo (3);.

test.array [1] = 2;

test.array [2] = 3;

test.show_element (0);

}

}

 

OUTPUT:

 

Exception: OutOfRange: An exception of type outOfRange was thrown. at Demo.show_element(Int32 i) in

Go:\cSharpEd\excep.cs:line 19

 

The above program can be simplified if you use a built in Exception class provided by the C# runtime. The full list of built in Exception classes hasn’t been published yet by Microsoft at the time of this writing.

         EXCEPTION HANDLING

In the following program we use built in ArgumentException instead of OutOfRange exception.

A better way to handle an Argument exception

 

using system;

class Demo

{

int n;

public int []array;

public Demo (int n)

{

this.array = new int En];

this.n= n;

},

pub1ic void· show_element (int i)

{

try

{

i f (I == 0)

throw new ArgumentException (“Out of rannge”);

}

catch (ArgumentException e)

{

console.writeLine(“Exception :{0}”,e);

return ;

}

Console.WriteLine (array[i]);

.}

}

class Test

{

public static void Main()

{

Demo test = new Demo(3);

test.array[l] = 2;

test.array[2] =3;

test.show_element (0);

}

}

Following the last ‘catch’ box you can also include a ‘finally’ box. This code is guaranteed to run whether or not an exception is generated. It is especially useful for cleanup code where this would be skipped in the ‘try’ box following an exception being thrown.

Where an exception is not caught by any of the subsequent ‘catch’ boxes, the exception is thrown upwards to the code which called the method in which the exception occurred (note that in C# the methods do not declare what exceptions they are throwing). This exception will keep on bubbling upwards until it is either caught by some exception handling in the code or until it can go no further and causes the program to halt.

Note that the exceptions a program throws need not be limited to those automatically generated. A program can throw exceptions-including customized exceptions-whenever it wishes, using· the ‘throw’ command. The code below gives examples of all the statements discussed above, with the ‘getException’ method showing how. to throw an exception.

 

using System;

public class ExceptionDemo

{

public static void Main ()

{

try

{

getException();

}

catch (Exception e)

{

Console.writeLine(“we got an exception”);

}

finally

{

Console.writeLine(“The end of the program”);

}

}

public static void getException()

{

throw new Exception();

}

}

FILE I/O in C#

By Dinesh Thakur

Files are the great way to store data between instances of your application, or file can be used to transfer data between applications. All input and output in the .NET framework involve the abstract base class Stream. The Stream class supports reading and writing bytes. Stream integrates asynchronous support. Its default implementations define synchronous reads and writes in terms of their corresponding asynchronous methods, and vice versa.

All classes that represent streams inherit from the’ Stream class. The Stream class and its derived classes provide a generic view of data sources and repositories, isolating the programmer from the specific details of the operating system and underlying devices.

Streams involve these fundamental operations:

• Streams can be read from.

Reading is the transfer of data from a stream into a data structure, such as an array of bytes.

• Streams can be written to.

Writing is the transfer of data from a data source into a stream.

• Streams can support seeking.

Seeking is the querying and modifying of the current position within a stream.

Depending on the underlying data source or repository, streams might support only some of these capabilities. For example, NetworkStreams do not support seeking there are type of streams:

 

• Output streams: These are used to write data on the external sources such as phesical disk file, a network location, a printer or another program.

• Input streams: These are used to read data into memory or variables that your program can access. Mostly used input stream is keyboard. An input stream can come from almost any source.

Classes for Input and Output

The System.IO namespace contains almost all of the classes for reading and writing data to and from files, you must reference this in your application to gain access to theses classes. Stream supports· synchronous and asynchronous reads and writes. The .NET Framework provides a number of classes derived from Stream, including FileStream, MemoryStream, and NetworkStream. In addition, there is a BufferedStream class, which provides buffered I/O and which can be used in conjunction with any of the other stream classes. The principal classes involved with I/O are summarized in Table.

       The principal classes

Reading Text File

 

The following code examples show how to read text from a text file. The second example notifies you when the end of the file is detected.

using System;

using System.IO;

 

class Test

{

public static void Main()

{

try

{

// Create an instance of StreamReader to read from a file.

// The using statement also closes the StreamReader.

using (streamReader sr = new streamReader(“TestFile.txt”))

{

string line;

// Read and disp1ay 1ines from the fi1e until the end of

// the file is reached.

while ((line = sr.Readline()) != null)

{

console.writeline(line);

}

}

}

catch (Exception e)

{

// let the user know what went wrong.

Conso1e.writeline( “The fi1e cou1d not be read:”);

Console.writeline(e.Message);

}

}

}

 

using System;

using system.IO;

public class TextFromFile

{

private const string FILE_NAME= “MyFile.txt”;

public static void Main(String[] args)

{

if (!File.Exists(FILE_NAME)).

{

console.writeLine(“{0} does not exist.”, FILE_NAME);

return;

}

using (streamReader sr = File.openText(FILE_NAME))

{

String input;

while ((input=sr.ReadLine())!=null)

{

console.writeLine(input);

}

Console.writeline (“The end of the stream has been reached.”);

sr.close();

}

}

 

Writing Text File

 

The first example shows how to add text to an e2cisting file. The second example shows how to create a new text file and write a string to it. Similar functionality can be provided by the WriteAlIText methods.

 

using system;

using system.Io;

class Test

{

public static void Main()

{

// Create an instance of streamwriter to write text to a

file.

// The using statement also closes the Streamwriter.

using (Streamwriter sw = new streamwriter(UTestFile.txt”))

{

// Add some text to the file.

sw.write(“This is the U);

sw.Writeline(‘header for the file.”);

sw.writeLine(“——-“);

II Arbitrary objects can also be written to the file.

sw.write(“The date is: ”);

sw.writeLine(DateTime.Now);

}

}

}

 

using system;

using system.Io;

public class TextToFile

{

private const string FILE_NAME = “MyFi1e.txt” ;

public static void Main(String[] args)

{

if (File.ExistS(FILE_NAME))·

{

Console.writeLine(“{O} already exists.”, FILE_NAME);

return;

}

using (streamwriter sw = File.createText(FILE_NAME))

{

sw.WriteLine (“This is my file.”);

sw.WriteLine (“I can write ints {OJ or floats {1}, and so

on. ” ,1, 4.2);

sw.close();

}

}

}

Reading and Writing to a Newly Created Data/Binary File

 

The BinaryWriter and BinaryReader classes are used for writing and reading data, rather than character strings. The following code example demonstrates writing data to and reading data from a new, empty file stream (Test. data). After creating the data file in the current directory, the associated BinaryWriter and BinaryReader are created, and the Binary Writer is used to write the integers 0 through 10 to Test.data, which leaves the file pointer at the end of the file. After setting the file pointer back to the origin, the BinaryReader reads out the specified content.

 

using system;

using System.IO;

class MyStream

{

private const string FILE_NAME = “Test.data”;

public static void Main(String[] args)

{

// Create the new, empty data f’l1e.

if (Fi1e.ExistS(FILE_NAME))

{

console.writeLine(“{O} already exists!”, FILE_NAME);

return;

}

Fi1eStream fs = new Filestream (FILE_NAME, FileMode.createNew);

// Create the writer for data.

Binarywriter w = new Binarywriter(fs);

// write data to Test.data.

for (int i = 0; i < 11; i++)

{

w.write( (int) i);

}

w.c1ose();

fs.c1ose();

// Create the reader for data.

fs = new FileStream(FILE_NAME, FileMode.open, Fi1eAccess.Read);

BinaryReader r = new BinaryReader(fs);

// Read data from Test.data.

for (int i = 0; i< 11; i++)

{

console.writeLine(r. ReadInt32 ());

}

r.C1ose();

fs.C1ose() ;

}

}

If Test.data already exists in the current directory, an IOException is thrown. Use FileMode.Create to always create a new file without throwing an IOException.

Console Input-Output in C#

By Dinesh Thakur

Console Input

The Console class allows using the Write () and the WriteLine () functions to display things on the screen. While the Console.Write () method is used to display something on the screen, the Console class provides the Read () method to get a value from the user. To use it, the name of a variable can be assigned to it. The syntax used is:

variableName = Console. Read();

This simply means that, when the user types something and presses Enter, what the user had typed would be given (the word is assigned) to the variable specified on the left side of the assignment operator.

Read() doesn’t always have to assign its value to a variable. For example, it can be used on its own line, which simply means that the user is expected to type something but the value typed by the user would not be used for any significant purpose. For example some versions of C# (even including Microsoft’s C# and Borland C#Builder) would display the DOS window briefly and disappear. You can use the Read() function to wait for the user to press any key in order to close the DOS window.

Besides Read(), the Console class also provides the ReadLine() method. Like the WriteLine() member function, after performing its assignment, the ReadLine() method sends the caret to the next line. Otherwise, it plays the same role as the Read() function.

 

string FirstName;

Console.write(“Enter First Name: “);

FirstName = console.ReadLine();

 

In C#, everything the user types is a string and the compiler would hardly analyze it without your explicit asking it to do so. Therefore, if you want to get a number from the user, first request a string. after getting the string, you must convert it to a number. To perform this conversion, each data type of the .NET Framework provides a mechanism called Parse. To use Parse(), type the data type, followed by a period, followed by Parse, and followed by parentheses. In the parentheses of Parse, type the string that you requested from the user.

 

Here is an example:

 

using system;

namespace GeorgetownCleaningservices

{

class orderprocessing

{

static void Main()

{

int Number;

string strNumber;

strNumber = console.ReadLine();

Number = int.parse(strNumber);

}

}

}

Console Output

Instead of using two Write() or a combination of Write() and WriteLine() to display data, you can convert a value to a string and display it directly. To do this, you can provide two strings to the Write() or WriteLine() and separate them with a comma:

1. The first part of the string provided to Write() or WriteLine() is the complete string that would display to the user. This first string itself can be made of different sections:

(a) One section is a string in any way you want it to display

(b) Another section is a number included between an opening curly bracket “{“and a closing curly bracket “}”.This combination of”{” and “}”is referred to as a, placeholder.

You can put the placeholder anywhere inside of the string. The first placeholder must have number O. The second must have number 1, etc. With this technique, you can create the string anyway you like and use the placeholders anywhere inside of the string

2. The second part of the string provided to Write() or WriteLine() is the value that you want to display. It can be one value if you used only one placeholder with 0 in the first string. It’ you used different placeholders, you can then provide a different value for each one of them in this second part, separating the values with a comma

Here are examples:

 

Demonstration of Writeline method

 

using System;

 

// An Exercise class

class Exercise

{

static void Main()

{

String FullName = “Anselme Bogos”;

int Age = 15;

double Hsalary = 22.74;

Console. writeline (“Full Name: {0}”, Full Name) ;

console.writeline(“Age: {0}”, Age);

console.writeline(“Distance: {0}”, Hsalary);

console.writeline(“Name: {0}\n Age: {1}\n Distance:{2}”,

FullName, Age, Hsalary);

Console.writeline();

}

}

 

OUTPUT:

 

Full Name: Anselme Bogos

Age: 15

Distance: 22.74

Full Name: Anselme Bogos

Age: 15

Distance: 22.74

 

As mentioned already, the numeric value typed in the curly brackets of the first part is an ordered number. If you want to display more than one value, provide each incremental value in its curly brackets. The syntax used is:

 

write(“To Display {0} {l} {2} {n}, First, second, Third, nth);

 

You can use the sections between a closing curly bracket and an opening curly bracket to create a meaningful sentence.

The System names pace provides a specific letter that you can use in the Write() or WriteLine()’s placeholder for each category of data to display. To format a value, in the placeholder of the variable or value, after the number, type a colon and one of the appropriate letter from the following table. If you are using ToStringO, then, in the parentheses of

ToString(), you can include a specific letter or combination inside of double-quotes. The letters and their meanings are:

                              Char used For

Use of particular character in writeline method

 

using System;

 

// An Exercise class

class Exercise

{

static void Main()

{

double Distance = 248.38782;

int Age = 15;

int Newcolor = 3478;

double Hsal = 22.74, Hrswork = 35.5018473;

double weeklysal = Hsal * Hrswork;

Console.writeLine(“Distance: {OJ”, Distance.ToString(“E”));

console.writeLine(“Age: {O}”, Age.ToStringO);

consol e.writeLine(“color: {O}”, Newcolor .Tostring(“x”));

Console.writeLine(“weekly salary: {OJ for .{1} hours”,

weeksal.ToString(“c”), Hrswork.ToString(“F”));

console.writeLine();

}

}

 

OUTPUT:

 

Distance: 2.483878E+002

Age: 15

color: D96

weekly salary: $807.31 for 35.50 hours

 

To specify the amount of space used to display a string, you can use its placeholder in Write() or WriteLine(). To do this, in the placeholder, type the 0 or the incrementing number of the placer and its formatting character if necessary and if any. Then, type a comma followed by the number of characters equivalent to the desired width. Here are examples:

 

Demonstration of Alinement in Writeline method

 

using System;

// An Exercise class

class Exercise

{

static void Main()

{

String Full Name = “Anselme 80gos”;

int Age = 15;

double Marks = 22.74;

 

console.writeline(“Full Name: {O,20}”, Full Name);

Console.writeline(“Age: {O,14}”, Age.ToString());

console.writeline(“Marks:{O:C,8}”, Marks.ToString());

Console. writeline(“——————————“) ;

Console.writeline();

}

}

 

OUTPUT:

 

Full Name:         Anselme bogos

Age: 15

Marks: $22.74

 

The sign you provide for the width is very important. If it is positive, the line of text is aligned to the right. This should be your preferred alignment for numeric values. If the number is negative, then the text is aligned to the left.

Operator Overloading in C#

By Dinesh Thakur

Another important and exciting feature object-oriented programming is Operator overloading. C# supports the concept of operator overloading.

Operator overloading is a concept in which operator can defined to work with the userdefined data types such as structs and classes in the same way as the pre-defined data types.

Consider an example:

 

Overloading on ‘+’ operator

 

using System;

public class Item

{

pub1ic int i;

public Item( int j)

{

i = j;

}

public static Item operator + ( Item x , Item y)

-{

system.console.writeLine(“operator +” + x.i +” “+ y.i);

Item z = new Item(x.i+y.i);

return z;

}

}

public class Test

{

public static void Main()

{

Item a = new Item(l0);

Item b = new Item(5);

Item c;

c = a + b ;

system.console.writeLine(c.i);

}

}

OUTPUT:

Operator + 10 5

15

The word operator as the name of a function, is legal and the only way to overload operators. We follow this word with the operator we want to overload and then the parameters we will call the operator with. + is a binary operator and will need two Item’s, one on its left and the other on its right. Then at beginning, we give the return value. of the operator. In our case we want a + to add two Item’s and return a third Item where i will be the sum of the individual i’s. Thus a+b will call the operator + with x being equal to a and y to b. Thus x.i will have a value 10 and y.i, 5. We are creating a new object z and in the constructor passing 15 i.e. 10 + 5. Thus the i of z will be 15 which is being returned. a + b will now be replaced by the object whose i has a value 15 and c will be equal to this object. Thus c.i will be equal to 15.

There are many operators that cannot be overloaded. Which are listed below:

• Conditional Operator                    & &, II

• Compound Assignment                +=, -=, *=, 1=, %=

• Other Operators                            [], 0, = , ?:, ->, new, sizeof, typesof, is, as

Multiple Calling of Overloaded Operator.

 

using system;

public class Item

{

pub1ic int i;

public Item( int j)

{

i = j;

}

public static Item operator + ( Item x , Item y)

{

system.console.writeLine(“operator +” + x.i +u ” + y.i);

Item z = new Item(x.i+y.i);

return z;

}

}

public class Test

{

public static void Main()

{

Item a = new Item(lO);

Item b = new Item(5);

Item c = new Item(2);

Item d;

d = a’+ b + c ;

system.Console.writeLine(d.i);

}

}

OUTPUT:

Operator + 10 5

Operator + 15 2

17

There is only change d = a + b + c from above example. C# gets easily confused with complex statements so it does not read all of it. It sees two operators on the same line. In this case, the same plus. An internal rule tells it to read the plus left to right i.e. it will only see a + b. It will call the operator + with x.i as 10 and y.i as 5 because a’s i is 10 and obi’s i is 5. This will create a temporary object like Item whose i is 15, lets call it zz. The object z is very different from zz. C# then evaluates zz + c. Thus x.i will display 15 and y.i will have the value of c.i i.e. 2. To support multiple invocations of the operator on a single line, the code does not change.

Versioning a .NET Assembly

By Dinesh Thakur

Application development as the name suggest is a development process. With time, new functionality is added to current applications and hence different versions of the application come to existence. Application development for quite sometime has been focused towards component oriented development. Hence an upgrade of the application definitely means an upgrade of the components. These components need to be versioned along with the application. Often components alone can face an upgrade-offering new functionality. When this happens, existing clients face a problem when the component they reference is upgraded. Net assemblies attempt to solve this problem by embedding the version information into the assembly itself. With the advanced capabilities of Windows 2000, two different assemblies can be loaded into the memory side-by-side.

we shall take a look at how developers can set version numbers for their .Net Assemblies and how these assemblies can be loaded side-by-side.

Versioning a .NET Assembly

An assembly version is a number, which basically consist of four parts. These four parts are

 

1. Major

2. Minor

3. Revision

4. Build

                  Versioning a .NET Assembly

Major/Minor Number: If there is a change in major or minor number, it indicates that the assembly is incompatible with the previous version of that assembly.

Revision Number: If there is a change in revision number, it indicates that the assembly may be compatible with the previous version of that assembly.

Build Number: If there is a change in build number, it indicates that a very minor change has been made to the assembly.

Version numbers for an assembly are set in AssemblyInfo.cs file (located in solution explorer of VS.NET).

The assemblyinfo.cs file contains assembly attributes for setting various metadata values for the assembly like company name, copyright statement and kind. The file also contains an assembly version attribute, which can be used to set the version number of the assembly.

 

Events in C#

By Dinesh Thakur

In object-oriented languages, objects expose encapsulated functions called methods. Methods are encapsulated functions which run when they are invoked.

Sometimes, however, we think of the process of method invocation more grandly. In such a case, the method invocation is termed an ‘event’, and the running of the method is the ‘handling’ of the event. An standard example of an event is a user’s selection of a button on a graphical user interface; this action may trigger a number of methods to ‘handle’ it

Events provide a way for a class or object to notify other classes or objects when something of interest happens. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.

Even modeling is fully based the delegate model of C# language. According to the event modeling, publishers send out their event only to subscribers who have subscribed to receive the specific event.

                          publishers send out their event only to subscribers who have subscribed to receive the specific event.

Let us look at how events are declare in C# syntax:

 

[modifier] event [type] [Event identifier];

In the above syntax, the modifier is any allowed scope modifier. The type must be delegate and the Event identifier is any valid identifier which you will refer in you program.

What distinguishes events from other method invocations is not, however, that they must   generated externally. Any internal change in the state of a program can be used as an event. Rather, what distinguishes events is that they are backed by a particular ‘subscription notification’ model. An arbitrary class must be able to ‘subscribe to’ (or declare its interest in) a particular event, and then receive a ‘notification’ (ie. have one of its methods run) whenever the event occurs.

Events have the following properties:

• The publisher determines when an event is raised, the subscribers determine what action is taken is response to the event.

• An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers.

• Events that the have no subscriber are never called.

• Events are commonly used to signal user actions such as button clicks or menu selection in graphical user interface.

• When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised.

• Events can be used to synchronize threads.

• In the .NET framework class library, events are based on the Event Handler delegate and the EventArgs base class.

Delegates (in particular multicast delegates) are essential in realizing this subscription notification model.

Here is the simple user defined event shown in sample example.

 

Simple userdefined Event.

 

using system;

public delegate void Edelegate();

public class sample

{

public event Edelegate eve; II Event declaration

public void first ()

{ Console.writeLine (“I am First”); }

public void second ()

{ console.writeLine (“I am second”); }

public void Third ()

{Console.writeLine (“I am Third”); }

public void eveCall ()

{ if (eve!=null) eve (); }

}

class Demo

{ pubic static void Main ()

{

sample s = new sample ();

S.eve + = new Edelegate (s.first);

S.evecall ();

console.writeLine (U “);

S.eve + = new Edelegate (S.second);

S.evecal1 ();

console.writeLine(U— ..-.-.–“);

S.eve + = new Edelegate (s.Third);

S.evecal1 ();

}

}

 

OUTPUT:

 

I am First         I am First

I am First         I am Second

I am Second    I am Third

 

Predefined Event of Timer.

 

using system;

using system.collections;

using system.Text;

using System.Timers;

 

class EventTest

{

 

static int counter = 0;

static string str = “This string will appear one letter at

a time.”;

 

static void Main(string[] args)

{

Timer myTimer = new Timer(lOO);

myTimer.Elapsed +=new ElapsedEventHandler(writeChar);

myTimer.Start();

console.ReadLine();

}

 

static void writechar(object source, ElapsedEventArgs e)

{

console.write (str[counter++ % str.Length]);

}

}

OUTPUT: (program wills tenninate by pressing any key)

This string will appear one letter at a time. This string will appear one letter at a time.

This string wills appea.

Tips for Events

The code above demonstrates some points about event-handling which are not enforced by the language architecture, bl,lt are used throughout the .Net framework as good practice.

1. When you want to raise an event in code, you don’t tend to trigger the class’s event object directly. Rather, you call a ‘protected, virtual’ method to trigger it (cf. the onMyEvent method above).

2. By convention, when events are raised they pass two objects to their subscribers. The first is a reference to the class raising the event; the second is an instance of the System.EventArgs class which contains any arbitrary data about the event

3. If an event is not interested in passing data to subscribers, then its defining delegate will still reference an EventArgs object (but a null value will be passed by the event).

If an event should pass data to its subscribers, however, then it is standard to use a specific class which derives from the EventArgs class to hold this data.

 

4. When you write a class which inherits from an event-raising base class, you can ‘intercept’ an event by overriding the method used to raise it. The following code illustrates such an intercept – classes which subscribe to the event will never receive notifications about it.

 

protected override void onMyEvent(EventArgs args)

{

console.writeLine(“hello”);

}

 

If you want subscribers to continue to receive notifications despite such an ‘intercepting’ method, however, then you can call the base class method as in the following:

 

protected override void onMyEvent(EventArgs args)

{

console.writeLine(“hello”);

base.onMyEvent(args);

}

Delegates in C#

By Dinesh Thakur

Delegate is a method template which used to implement the concept of function pointer.

 

The C and C++ languages are having the concept of function pointer. This was even more useful when programming for the Microsoft Windows operating systems because the Win32 library relies on the concept of callback functions. Callback functions are used in Microsoft Windows programming to process messages. For this reason and because of their functionality, callback functions were carried out in the .NET Framework but they were defined with the name of delegate.

~ Concept

A delegate is a special type of user-defined variable that is declared globally, like a class.

In fact, a delegate is created like an interface but as a method. Based on this, a delegate interface, a delegate is not defined. Its role is to show what a useful method would look like.To support this concept, a delegate can provide all the necessary information that would be used on a method. This includes a return type, no argument or one or more Argument.

Delegate Declaration and Instantiation

Delegates can be specified in their own namespace, or else can ‘be specified within other class. In each case, the declaration specifies a new class, which inherits from System.MulticastDelegate.

Each delegate is limited to referencing methods of a particular kind only. The type is indicated by the delegate declaration – the input parameters and return type given in the delegate declaration must be shared by the methods its delegate instances reference. To illustrate this: a delegate specified as below can be used to refer only to methods which have a single String input and no return value:

 

public delegate void print (String s);

 

Suppose, for instance, that a class contains the following method:

 

public void realMethod (String myString)

{

// method code

}

Another method in this class could then instantiate the ‘Print’ delegate in the following way, so that it holds a reference to ‘realMethod’:

 

print delegatevariable = new print(realMethod);

We can note two important points about this example. Firstly, the unqualified method passed to the delegate constructor is implicitly recognised as a method of the instance passing it. That is, the code is equivalent to:

 

Print delegatevariable = new print (this.realMethod);

We can, however, in the same way pass to the delegate constructor the methods of other class instances, or even static class methods. In the case of the former, the instance must exist at the time the method reference is passed. In the case of the latter (exemplified below), the class need never be instantiated.

 

Print delegatevariable = new

print(ExampleClass.exampleMethod);

 

Use of delegate

 

using System;

//delegate declaration

delegate int operation(int x, int y);

class MathOpr

{

public static int Add(int a,

{

return(a + b); }

public static int Sub(int a,

{

return( a – b); }

public static int Mul(int a,

{

return( a * b);

}

}

class Test

{

public static void Main () {

}

//delegate instances

operation opr1 = new operation (Mathopr.Add);

operation opr2 = new operation (Mathopr.sub);

operation opr3 = new operation (Mathopr.Mul);

 

//invoking of delegates

int ans1 = opr1(200, 100);

int ans2 = opr2(200, 100);

int ans3 = opr3(20,10);

 

Console.writeLine(“\n Addition :”+ ans1);

console.writeLine(“\n Subtraction :”+ ans2);

Console.writeLine(“\n Multiplication :”+ ans3);

}

}

 

OUTPUT:

Adiition: 300

Subtraction: 100

Multiplication: 200

Multicast Delegates

The second thing to note about the example is that all delegates can be constructed in this fashion, to create a delegate instance which refers to. a single method. However, as we noted before, some delegates-termed ‘multicast delegates‘ – can simultaneously reference multiple methods. These delegates must-like our Print delegate – specify a ‘void’ return type•

One manipulates the references of multicast delegates by using addition and subtraction.

The following code gives some examples:

print s = null;

s = s + new print (realMethod);

s += new print (otherRealMethod);

The – and – = operators are used in the same way to remove method references from a delegate.

The following code gives an example of the use of multicast delegates.

Use of Multicast delegates

 

using system;

delegate void Multiel();

class MD

{

static public void Hello()

{

console.writeLine(“Hello”);

}

static public void show()

{

console.writeLine(” Hi”);

}

}

class Test

{

public static void Main()

{

//delegate instances

Multioel Ml = new Multioel(Mo.Hello);

Multioel M2 = new Multioel(Mo.hello);

}

/combine the delegates

Multioel M3 = Ml + M2;

Multioel M4 = M2 + Ml;

//extracting the delegates

Multioel M5 = M3 – M2;

Multioel M6 = M4 – Ml;

//invoking delegates

M3 () ;

M4();

M5();

M6();

}

}

 

OUTPUT:

Hello

Hi

Hi

Hello

hello

Hi

Delegates vs. Interface

Delegates and interfaces are similar in that they enable the aspiration of specification and implementation. Multiple independent authors can produce implementations that are compatible with an interface specification. Similarly, a delegate specifies the signature of a method, and authors can write methods that are compatible with the delegate specification. When should you use interfaces, and when should you use delegates?

Delegates are useful when

• A single method is being called.

• A class may want to have multiple implementations of the method specification.

• It is desirable to allow using a static method to implement the specification.

• An event like design pattern is desired.

• The caller has no need to know or obtain the object that the method is defined on.

• The provider of the implementation wants to “hand out” the implementation of the specification to only a few selected components.

• Easy composition is desired

Interfaces are useful when:

• The specification defines a set of related methods that will be called.

, • A class typically implements the specification only one.

• The caller of the interface wants to cast to or from the interface to obtain interface or classes.

Indexers in C#

By Dinesh Thakur

An indexer is a member that enables objects to be indexed in the same as an array.

If properties are ‘virtual fields‘, indexers are more like ‘virtual arrays‘. Indexers permit instances of a class or struct to be indexed in the same way as arrays. Indexers are similar to properties except that their accessors take parameters. They allow a class to emulate an array, where the elements of this array are actually dynamically generated by function calls.

An indexer is declared like a property except that the name of the member is this followed by a parameter list written between the delimeters [ and ]. The paramaters are available in the accessor(s) of the indexer. Similar to properties, indexers can be read-write, readonly, and write only and the accessor of an indexer can be virtual.

 

The following piece of code defines a class to hold a list of runners in an athletics race. The runners are held in lane order, and an indexer is exposed which allows the list to be both read from and written to. The indexer deals gracefully with cases in which the lane number passed to it is either too high or too low.

 

class RaceDetails

{

private string[] lanes;

public RaceDetails()

{

this.lanes = new strings[8];

}

public string this[int i]

{

get

{

return (i>=0 && i<8) ? this.lanes[i] : “error”;

 

}

set

{

if (i>=0 && i<8)

this.lanes[i] = value;

}}

}

 

 

The following simple code illustrates use being made of the class just defined. The name of the person in the race’s first lane is set, and then this name is sent to a console window.

 

RaceDetails rd = new RaceDetails();

rd[0] = “fred”;

Console.writeLine (“lane One :” + rd[0]) ;

 

As can be seen from the example, an indexer is defined in a similar way to a property. One important difference is in the indexer’s signature; the word ‘this’ is used in place of a and after this word indexing elements are provided.

~ Concept

Indexers aren’t differentiated by name, and a class cannot declare two indexers with the same signature. However, this does not entail that a class is limited to just one indexer. Different indexers can have different types and numbers of indexing elements (these being equivalent to method parameters, except that each indexer must have at least one indexing element, and the ‘ref and ‘out’ modifiers cannot be used).

Because indexing elements are not limited to integers, the original description of indexers as ‘virtual arrays’ actually rather undersells them. For example, where the indexing elements include strings, indexers present themselves more like hash tables.

The following code shows an implementation for the RaceDetails class of an indexer whose indexing element is a string. Using this indexer it is possible to refer to a lane using the name of the person currently filling that lane.

 

public string this[string s]

{

get

{

Int laneNum = getposition(s);

return (laneNum<0) ? “error” : this.lanes[laneNum];

}

set

{

int laneNum = getposition(s);

if (laneNum>=0) this.lanes[laneNum] = value;

}

}

private int getposition(string myName)

{

for (int x=0; x<lanes.Length; x++)

{

if (myName==lanes[x]) return x;

}

return -1;

}

The following piece of code gives an example of the kind of use one might make of this string indexer.

 

rd[“fred”] = “j ill”;

After the execution of this code, the name “fred” will be replace with name the “jill” in object array ‘rd’. The string indexer will return index number of “fred” where “jill” will be aced.

The following example shows how to declare a private array field, myArray, and an. sing the indexer’ allows direct access to the instance b [i] The alternative to using the indexer is to declare the array as a public member and access its membersmyArray [i] directly.

 

Indexer

 

using System;

class indexerclass

{

private int[] myArray = new int [100];

public int this [int index] //indexer declaration

{ 

get

{

// Check the index limits

if (index < 0 //dex >,:, = 100)

return 0;

else

return myArray [index];

}

set

{

if (! (index < 0 Ilindex > = 100)

myArray [index] = value;

}

}

}

public class Mainclass

{

public static void Main()

{

Indexerclass b = new IndexerClass();

// call the indexer to initialize the elements # 3 and # 5.

b[3] = 256;

b(5] = 1024;

for (int i = 0; i < 10; i++)

{

Console.writeLine (“element” {0} = {1}”, i, b[i]);

}

}

}

 

OUTPUT:

 

Element # 0 = 0

Element # 1 = 0

Element # 2 = 0

Element # 3 = 256

Element # 4 = 0

Element # 5 = 1024

Element # 6 = 0

Element # 7 = 0

Element # 8 = 0

Element # 9 = 0

Element # 10 = 0

 

Notice that when an indexer’s access in evaluated (for example in a Console.Writer statement) the get accessor is invoked. Therefore, if no get accessor exists a compile-time error occurs.

 

Comparison between Properties and Indexers

 

Indexers are similar to properties. Except for the difference shown in the following table, all of the rules defined for property accessors apply to indexer accessor as well.

                         Comparison between Properties and Indexers

Properties in C#

By Dinesh Thakur

Property is a feature to add more smartness to data fields for get and set the value.

Properties are named members of classes, structs and interfaces. They provide a flexible mechanism to read, write, or compute the values of private fields through accessors. Properties can be thought of as virtual fields. From the outside, a class’ property looks just like a field. But from the inside, the property is generated using the actual class fields.

Property declarations take just those modifiers taken by methods. Unlike languages like Java,C# provides dedicated support for accession and mutation of these properties. Suppose, for instance, that a type contains an internal field called ‘age’. With the following code one could specify a property Age, providing accessors and mutators to this internal field

 

public int Age

{

get

{

return this.age;

}

set

{

this.age = value;

}

}

Notice that the term ‘value’ is used in the above .piece of code. This variable always holds

the value passed to the ‘set’ block.· For instance, the execution of the following line of ode (assuming the appropriate class instance) would automatically set ‘value’ in the ‘set’ block to 4.

person.Age = 4;

This property Age can be described as ‘read-write’ since it can be both read from and written to. To make a property ‘write-only’ one simply does not specify a ‘get’ block; to make it ‘readonly’ one does not specify a ‘set’ block. The following piece of code demonstrates the read-only property ‘Adult’:

 

public bool Adult

{

get

{

if (this.age<18)

       return false;

else

return true;

}

}

A property declared using the static modifiers is classified as a static property; otherwise, it is classified as an instance property. Like other static members, a static property is not associated with a specific instance and cannot be referenced through an instance. Instead, it is associated with the type and can only be referenced an instance. Instead, it is associated with the type and can only be referenced through the type name. For example, in the following statements:

 

Button okButton = new Button();

// using an instance property

string s = okButton.caption;

the caption property is associated with the instance okButton. If caption is as a static property, the class name (Button) must be used instead :

// using static property

strings = Button. Caption;

An instance of a class can be accessed using this in the accessors of an instance property, but it is an error to use this in the accessors of a static property. It is an error to use a virtual, abstract, or override modifier on an accessor of a static property.

The following example demonstrates instances, static and read-only properties. It accepts the name of the employee from the keyboard, increments number of Emp by 1, and displays the Employee name and number.

 

Use of property.

 

using system;

public class Employee

{

public static int numberofEmp;

private static int counter;

private string name;

public string Name

{

   get

         {

   return name;

         }

   set

       {

         name = value;

}

}

public static int Counter

{

get

{

return counter;

}

set

{

counter = value;

}

}

public Employee()

{

Counter = ++ Counter + numberofEmp;

}

}

public class MainClass

{

public static void Main()

{

Employee.numberofEmp = 100;

Employee e1 = new Employee();

e1.Name = “deepika”;

console.writeline (“Employee number: {O}”, Employee.counter);

console.writeline (“Employee name: {O}”, e1.Name);

}

}

 

OUTPUT:

 

Employee number: 101

Employee name: Deepika

Accessors

The accessor of a property contains the executable statements associated with getting (reading or computing) or setting (writing) the property. The accessor declarations take the following forms:

 

set {accessor body}

get {accessor body}

where, accessor body is a block that contains the statements to be executed when the accessor is invoked.

 

The get Accessor

 

The body of the get accessor is similar to that of a method. It must return a value of the property type. The execution of the get accessor is.equivalent to reading the value of the field.

The following is a get accessor that returns the value of private field name :

 

private string name; II the name field

public string Name II the Name property

{

get

{

return name;

}

}

When you reference the property, except as the target of an assignment, the .get accessor is invoked to read the value of the property. For example:

Emp1oyee el = new Employee ();

–

–

console.write (el.Name); II The get accessor is invoked here

The get accessor must terminate is a return or throw statement and control can not flow off the accessor body.

The set Accessor

The set accessor is similar to a method that returns void. It uses an implicit parameter called value, whose type is the type of the property. In the following example, a set accessor is added the Name property.

public string Name

{

       get

     {

             return name;

       }

       set

     {

             name = value;

       }

}

When you assign a value to the property, the set accessor is invoked with an argument that provides the new value. For example:

 

e1 .Name = “Deepika”, // The set accessor is invoked here

It is an error to use the implicit parameter name (value) for a local variable declaration in a set accessor.

A property is classified according to the accessors used as follows:

• A property with a get accessor only is called a read-only property. You can not assign a value to a read-only property.

• A property with a set accessor only is called write-only property. You can not reference a write only property except as a target of an assignment.

• A property with both get and set accessors is a read-write property.

In a property declaration, both the get and set accessor must be declared inside the body of the property.

What is SYSTEM.COLLECTION CLASSES in C#?

By Dinesh Thakur

The Collection namespace of System contains many classes and interfaces, which provides to define various collections of objects. These interfaces and classes are useful for every programmer to develop big or large applications.

 

The .NET Framework provides a rich suite of collection classes, including Array, ArrayList, NameValueCollection, StringCollection, Queue, Stack, and BitArray.

 

Arrays in C# are implemented as instance of System.Array class, and are just one type known as collection classes.

System.Array

 

The Array class has a number of useful methods which extend the capabilities of arrays and make them smarter than arrays seen in other languages.

                   System.Array class, and are just one type known as collection classes

Two useful static methods of Array are Sort( ) and Reverse( ).These are fully supported for the built-in C# types such as string. Example demonstrates the use of these two methods to manipulate String objects

 

Using Array.Sort and Array.Reverse

 

using System;

using System.collections;

public class Tester

{

public static void printMyArray(object[] Arr)

{

foreach (object obj in Arr)

console.writeline(“value: {O}”, obj);

 

Console.writeline(“\n”);

}

static void Main()

{

String[] Arr1 ={“world”, “is”, “Beautiful”};

console.writeline(“Original array is :”);

printMyArray(Arr01);

Array.Reverse(Arr1);

Console.writeline(“After reverse array is :”);

printMyArray(Arr1);

 

String [] Arr2 ={“see”,”it” ,”from” ,”your” ,”heart” ,”eyes”};

 

console.writeline(“Original array is :”);

printMyArray(Arr2);

Array.sort(Arr2);

console.writeline(“After sort array is :”);

printMyArray(Arr2);

}

}

 

OUTPUT:

 

Original Array is:

Value: World

Value: is

Value: Beautiful

After Reveres Array is:

Value: Beautiful

 

Value: is

Value: World

 

Original Array is:

Value: See

Value: it

Value: from

Value: your

Value: heart

Value: eyes

 

After Sort array is:

Value: eyes

Value: from

Value: heart

Value: it

Value: See

Value: your

 

The .NET Framework provides standard interfaces for enumerating, comparing, and creating collections. The key collection interfaces are listed.

                    key collection interfaces are listed

The System.Array class inherits from IList, ICollection, and IEnumerable interfaces, but doesn’t support some of more advanced features of IList and represents, a list of items with a fixed size.

ArrayLists

The classic problem with the Array type is its fixed size. If you do not know in advance how many objects an array will hold, you run the risk of declaring either too small an array (and running out of room) or too large an array (and wasting memory).

Your program might be asking the user for input, or gathering input from a web site. it finds objects (strings, books, values, etc.) you will add them to the array, but you have no idea how many objects you’ll collect in any given session. The classic fixed-size array is not a good choice, as you can’t predict how large an array you’ll need.

The ArrayList class is an array whose size is dynamically increased as required. ArrayLists provide a number of useful methods and properties for their manipulation.

When you create an ArrayList, you do not define how many objects it will contain. You add to the ArrayList using the Add( ) method, and the list takes care of its own internal bookkeeping, as illustrated in simple.

 

Working with an ArrayList

 

using system;

using system.collections;

public class Tester

{

static void Main( )

{

ArrayList number = new ArrayList( );

 

//adding the elements to ArrayList

foreach(int num in new

int[10]{10,9,10,23,45,56,9,12,78,64})

{

number.Add(num);

}

//adding another item out of loop

Number.add(34);

//remove first element whose value is 9

Number.remove(9);

//remove the element of 7th position

Number.removeat(6);

//display the content of arraylist

Console.writeline(“:element of arraylist”);

For(int i=0;i!=number.count;i++)

{

Int num =(int)number[i];

Console.write(num + “,”);

}

//sort the existing elements of ArrayList

number.sort();

console.writeLine(“\nsorted List”);

.for(int i=O;i!=number.count;i++)

{

int num =(int)number[i];

console.write(num+”,”);

}

}

}

 

OUTPUT:

 

Elements of ArrayList

10,10,23,45,56,9,78,64,34

Sorted List

9,10,10,23,34,45,56,64,78

Queue

A queue represents a first-in, first-out (FIFO) collection. The classic analogy is to a line at a ticket window. The first person in line ought to be the first person to come off the line to buy a ticket.

A queue is a good collection to use when you are managing a limited resource. For example, you might want to send messages to a resource which can only handle one message at a time.

You would then create a message queue so that you can say to your clients: “Your message is important to us. Messages are handled in the order in which they are received.”

You can add elements to your queue with the Enqueue command and you can take them off the queue with Dequeue or by using an enumerator.

 

Working with a queue

 

using System;

using system.collections;

public class Tester

{

static void Main( )

{

Queue number = new Queue( );

 

//adding the elements to Queue

foreach(int num in new

int[lO]{lO,9,lO,23,45,56,9,12,78,64})

{

number.Enqueue(num);

}

//adding another item out of loop

number.Enqueue(34)

 

// remove first element

number.Dequeue();

 

II view the first element in the

II Queue but do not remove.

Console.writeLine(“\n(peek) \t{O}”, number.peek( ) );

 

//display the content of Queue

console.writeLine(“\ncontents of Queue”);

printvalues(number);

 

}

public static voidprintvalues( IEnumerable mycollection )

{

IEnumerator myEnumerator = mycollection.GetEnumerator( );

while ( myEnumerator.MoveNext( ) )

console.write( “{O} “,myEnumerator.current );

Console.writeLine( );

}

}

 

OUTPUT:

 

(peek)     9

Contents of Queue:

9 10 23 45 56 9 12 78 64 34

Stacks

A stack is a last-in, first-out (LIFO) collection, like a stack of dishes at a buffet table, or a stack of coins on your desk. You add a dish on top, and that is the first dish you take off   the stack.

The principal methods for adding to and removing from a stack are Push( )and Pop( ); Stack also offers a Peek( ) method, very much like Queue.

The ArrayList, Queue, and Stack types contain overloaded CopyTo( ) and ToArray( ) methods for copying their elements to an array. In the case of a Stack, the CopyTo( ) method will copy its elements to an existing one-dimensional array, overwriting the contents of the array beginning at the index you specify. The ToArray( ) method returns a new array with the contents of the stack’s elements.

 

Working with a Stack

 

using System;

using System.collections;

public class Tester

{

static void Main( )

{

stack intStack = new Stack( );

 

II populate the array

for (int i = 0;i<8;i++)

{

intStack.push(i*5);

}

// Display the stack.

console.write( “intStack values:\t” );

printvalues( intStack );

 

// Remove an element from the stack

Console.writeLine( “\n(pop)\t{O}”, intstack.pop( ) );

 

// Display the stack

Console.write( “intStack values:\t” );

printvalues( intStack );

 

// Remove another element from the Stack

Console.writeLine( “\n(pop)\t{O}”, intStack.pop( ) );

 

// display the Stack

console.write( “intstack values:\t” );

printvalues( intStack );

 

// view the first element in the

// Stack but do not remove.

Conso1e.writeLine ( “\n(peek) \t{O}”, intStack .Peek( ) );

 

// Display the Stack

Console.write( “intStack values:\t” );

printvalues( intStack );

 

}

public static void printvalues( IEnumerable mycollection )

{

IEnumerator myEnumerator = myCollection.GetEnumerator( );

while ( myEnumerator.MoveNext( ) )

console.write( ”{0} “,myEnumerator.current );

console.writeLine( );

}

}

 

OUTPUT:

 

intStack values: 35 30 25 20 15 10 5 0

(Pop) 35

intStack values: 30 25 20 15 10 5 0

(Pop) 30

intStack values: 25 20 15 10 5 0

(Peek) 25

intStack values: 25 20 15 10 5 0

Hashtables

A hashtable is a dictionary optimized for fast retrieval. In a Hashtable, each value is stored in a “bucket.” The bucket is numbered, much like an offset into an array.

Because the key may not be an integer, it must be possible to translate the key (e.g., “Massachusetts”) into a bucket number. Each key must provide a hash code, a GetHashCode ( ) method will accomplish this magic.

You will remember that everything in C# derives from object. The object class provides a virtual method GetHashCode( ), which the derived types are free to inherit as is or to override. A trivial implementation of a GetHashCode( ) function for a string might  simply add up the Unicode values of each character in the string and then use the modulus operator to return a value between 0 and the number of buckets in the Hashtable. It is not necessary to write such a method for the string type, however, as the CLR provides one for you.

When you insert the values (the state capitals) into the Hashtable, the Hashtable calls GetHashCode( ) on each key we provide. This method returns an int, which identifies the bucket into which the state capital is placed.

It is possible, of course, for more than one key to return the same bucket number. This is called a collision. There are a number of ways to handle a collision. The most common solution, and the one adopted by the CLR, is simply to have each bucket maintain an ordered list of values. When you retrieve a value from the Hashtable, you provide- a key. Once again the Hashtable calls GetHashCode( ) on the key and uses the returned int to find the appropriate bucket. If there is only one value, it is returned. If there is more than one value, a binary search of the bucket’s contents is performed. Because there are few values, this search is typically very fast. see an example

 

Working with a HashTable

 

using System;

using System.collections;

 

// a simple class to store in the array

public class Tester

{

static void Main( )

{

// Create and initialize a new Hashtable.

Hashtable hashTable = new Hashtable( );

hashTable.Add(“000440312”, “Jesse Liberty”);

hashTable.Add(“OOOl23933″, ‘~Stacey Liberty”);

hashTable.Add(“000145938”, “John Galt”);

hashTable.Add(“000773394”, “Ayn Rand”);

// access a particular item

console.writeLine(“{O} “,hashTable[“000145938”]);

}

}

 

OUTPUT:

 

John Galt

SortedList

Some times you might want to provide a mapping where the type you map from isn’t int but rather some other type (string, double). The SortedList class provides this functionality by internally maintaining two objects arrays- one for keys, one for values.

The key array is always sorted.

In contrast to other collection classes, you don’t have control of where the element live in a SortedList. A SortedList can’t contain duplicate keys. however, if you use the squre bracket notation to add a key/value pair, then its ok.

When use a foreach statement to iterate a SortedList, you get back a DictionaryEntry which provides access to the elements in both arrays thru the Key property and Value property.

 

using System;

using System.collections;

public class Tester

{

 

static void Main( )

{

       SortedList map = new SortedList();

       string[] keys = {“these”,”are”,”the”,”keys”};

 

//adding the elements to sortedList

for(int i=O;i!=keys.Length;i++)

{

string k = keys[i];

int v = i;

map[k] = v;

}

console.writeLine(“\ncontent of SortedList”);

foreach(dictionaryEntry element in map)

{

string k = (string) element.Key;

int v = (int)element.value;

console.writeLine(“key: {O},\tvalue: {l}”,k,v);

}

}

}

 

OUTPUT:

 

Content of SortedList

 

key: are, Value: 1

key: keys, Value: 3

key: the, Value: 2

key: these, Value: 0

What is Polymorphism in C#

By Dinesh Thakur

Method overriding means same name methods in different classes.

Polymorphism is a feature to use one name in many forms. There ·Polymorphism can be achieved in following ways in C#:

• Method Overloading
• Method Overriding
• Method Hiding

Method overloading, means multiple methods of same name with different arguments in a single class or program. Method overriding and hiding makes use of the following three method-head keywords

• new
• virtual,
• override

The main difference between hiding and overriding relates to the choice of which method to call where the declared class of a variable is different to· the run-time class of the object it references. This point is explained further below.

Method Overriding

Suppose that we define a Square class which inherits from a Rectangle class (a square being a special case of a rectangle). Each of these classes also specifies a ‘getarea’ instance method, returning the area of the given instance.

For the Square class to ‘override’ the Rectangle class’ getArea method, the Rectangle class’ method must have first declared that it is happy to be overridden. One way in which it can do this is with the ‘virtual’ keyword. So, for instance, the Rectangle class’ getArea method might be specified like this:

publicvirtualdouble getArea(){return length * width;}

To override this method the Square class would then specify the overriding method with the ‘override’ keyword. For example: 

publicoverridedouble getArea(){return length * width;}

Note that for one method to override another, the overridden method must not be static, and it must be declared as either ‘virtual’, ‘abstract’ or ‘override’. Furthermore, the access modifiers for each method must be the same.

The major implication of the specifications above is that if we construct a new Square instance and then call its ‘getArea’ method, the method actually called will be the Square instance’s getArea method. So, for instance, if we run the following code: 

square sq =new Square(S);

double area = sq.getArea();

then the getArea method called on the second line will be the method defined in the Square class.

There is, however, a more subtle point. To show this, suppose that we declare two variables in the following way:

Square sq =new square(4);

Rectangle r = sq;

Here variable r refers to sq as a Rectangle instance (possible because the Square class· derives from the Rectangle class). We can now raise the question: if we run the following code 

double area = r.getArea();

then which getArea method is actually called – the Square class method or the Rectangle class method.

The answer in this case is that the Square class method would still be called. Because the Square class’ getArea method ‘overrides’ the corresponding method in the Rectangle class, calls to this method· on a Square instance always ‘slide through’ to the overriding method.

Method Overriding

using system;

class demo {

   class A {

       publicvirtualvoid show(){

               console.writeLine(“I am A“);

       }

    }

   class B:A {

        publicoverridevoid show(){

               console.writeLine(“I am B“);

        }

    }

    class C:A {

        publicoverridevoid show(){

               console.writeLine(“I am c“);

        }

     }

        publicstaticvoid Main(){

              A o;

              o =new B();

              o.show();

              o =new c();

              o.show();

         }

}

OUTPUT:

I am B

I am c

Method hiding

Where one method ‘hides’ another, the hidden method does not need to be declared with any special keyword. Instead, the hiding method just declares itself as ‘new’, So, where the Square class hides the Rectangle class’ getArea method, the two methods might just be written thus:

publicdouble getArea()// in Rectangle {

     return length * width;

}}

publicnewdouble getArea()// in Square {

    return length.* length;

}}

Note that a method can ‘hide’ another one without the access modifiers of these methods being the same. So, for instance, the Square’s getArea method could be declared as private, viz:

Private newdouble getArea(){

      return length * length;

}

This leads us to an important point. A ‘new’ method only hides a super-class method with a scope defined by its access modifier. Specifically, where the access level of the hiding method is ‘private’, as in the method just described, this method only hides the super-class method for the particular class in which it is defined.

To make this point more concrete, suppose that we introduced a further class, SpecialSquare, which inherits from Square. Suppose further that SpecialSquare does not overwrite the getArea method. In this case, because Square’s getArea method is defined as private, SpecialSquare inherits its getArea method directly from the Rectangle class (where the getArea method is public).

The final point to note about method hiding is that method calls do not always ‘slide through’ in the way that they do with virtual methods. So, if we declare two variables thus:

Square sq =new square(4);

Rectangle r = sq;

then run the code double area = r.getArea();

the get Area method run will be that defined in the Rectangle class, class, not the Square class.

Method hiding

using System;

class demo {

    class A {

         public virtual void show() {

              console.writeLine(“1 am A”);

         }}

    class B:A {

         public new void show() {

               console.writeLine(“I am B“);

        }}

    class B:A {

        public new void show() {

               console.writeLine(“I am e“);

       }}

       public static void Main() {

           A o;

           o = new B();

           o.show();

           o = new e();

           o.show();

   }

}

OUTPUT:

I am A

I am A

Type of Inheritance in C#

By Dinesh Thakur

Inheritance is a mechanism of sharing the members among the classes. Inheritance means taking an existing class and adding functionality by deriving a new class from it. The class you start with is called the base class, and the new class you create is called the derived class. [Read more…] about Type of Inheritance in C#

Type of Constructor

By Dinesh Thakur

Constructor is method of class to allocate the memory of object and initialize the variables of class.

 

When you declare a variable of a class, a special method must be called to initialize the members of that class. This method is automatically provided for every class and it is called a constructor.

Default Constructor

Whenever you create, a new class, a constructor is automatically provided to it. This particular constructor is called the default constructor. You have the option of creating it or not. Although a constructor is created for your class, you can customize its behavior or change it tremendously.

 

A constructor holds the same name as its class and doesn’t return any value, not even void. Here is an example:

 

public class Exercise

{

public void welcome ()

{

console.writeline (“This is an Exercise”);

}

Public exercise ()

{

}

}

 

Like every method, a constructor can be equipped with a body. In this body, you can access any of the member variables (or methods(s) of the same class. When introducing classes other than the main class, we saw that, to use such a class, you can declare its variable and allocate memory using the new operator. You can notice that we always included the parentheses when declaring such a variable. Here is an example:

 

public class class!

{

static void Main()

{

Exercise exo = new Exercise();

}

}

In this case, the parentheses indicate that we are calling the default constructor to instantiate the class.

Consider the following Example:

 

The demonstration of constructor.

 

using System;

public class Exercise

{

public void welcome()

{

console.writeLine(“The wonderful world of c# programming”);

}

console.writeLine(“The Exercise class is now available”);

public Exercise()

{

}

}

public class class! r

t

static void Main()

{

Exercise exo = new Exercise();

}

}

 

OUTPUT:

 

The Exercise class is now available

This shows that, when a class has been instantiated, its constructor is the first method to be called. For this reason, you can use a constructor to initialize a class, that is, to assign default values to its member variables. When a constructor is used to initialize a variable declared for a class. That constructor is referred to as an instance constructor.

Parameterized Constructor

We saw that there is always a default constructor for a new class that you create; you just the option of explicitly creating one or not. The default constructor as we saw it doesn’t take arguments: this is not a rule, it is simply assumed. Instead of a default constructor, you may want to create a constructor that takes argument. Here is an example:

 

public class Quadrilateral

{

public Quadrilateral(double side)

{

}

}

With this type of constructor, when you declare an instance of the class, you can use this new constructor to initialize the class. Here is an example:

 

using System;

public class Quadrilateral

{

public Quadrilateral(double side)

{

}

}

public class classl

{

static void Main()

{

Quadrilateral Square = new Quadrilateral(6.55);

}

}

If you create one constructor for your class and pass at least one argument to that constructor, the automatic default constructor created by the compiler disappears. This implies that if you declare an instance of the class and use the default constructor to initialize it, you would receive an error when you compile the program. Based on this rule, the following program will not compile:

 

using System;

public class Quadrilateral

{

public Quadrilateral(double side) {

}

}

public class Classl

{

static void Main()

{

Quadrilateral Square = new Quadrilateral();

}

}

If you still want to use the default constructor in a class after creating a constructor that takes at least one argument, you must explicitly create that default constructor.

Private Constructor

A private constructor is a special instance (default) constructor. It is commonly used in class that contain static members only, if a class has one or more private constructors and no blic constructors, then other classes (except nested ‘classes) are not allowed to create instances of this class. For example-

Class NLog

{

II private constructor

private NLog() { }

 

public static double e = 2.71828;

}

The declaration of the empty constructor prevents the automatic generation of a default constructor. Note that if you don’t use an access modifier with the constructor it will still be private by default. However, the private modifier is usually used explicitly to make it clear that the class cannot be instantiated.

Private constructors are useful to prevent creation of a class when these are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.

The following is an example of a class using a private constructor.

 

using System;

public class Myclass

{

private Myclass() {}

public static int counter;

public static int InerementCounter()

{

return ++counter;

}

}

 

 

class MainClass

{

static void Main ()

{

II if you uncomment the following statement, it will generate

II an error because the constructor is inaccessible

II Myclass myobject = new Myclass(); //error

Myclass.counter = 100;

Myclass.lncrementcounter();

Console.wr;teL;ne (“New count: {O}”, Myclass.counter);

}

}

 

OUTPUT:

 

New count : 100

Notice that is you uncoment the following statement from the example, it will generate

an error because the constructor is in assessable due to its protection level : /I Myclass Myobject

= new MyClass 0;// error.

Static Constructor

Like the above described instance constructors, a static constructor is used to initialize a class. The main difference is that a static constructor works internally, in the class. Therefore, it is not used to initialize a variable of the class and you can never declare a variable of a class using a static constructor.

To make a constructor static, when creating it, type the static keyword to its left. Here is an example:

 

using system;

public class Quadrilateral

{

static Quadrilateral()

{

}

}

public class class1

{

static void Main()

{

/* use the default constructor to initialize an

instance of the class */

Quadrilateral Square = new Quadrilateral

}

}

In the above class, a static constructor is created for the class but the default constructor is still available and it is used to instantiate the class. Notice· that. static constructors are not inherited, and cannot be called .directly.

After the class loader loads a class that will soon be used, but before it continues normal execution, it executes the static constructor for that class. Because of this process, you are guaranteed that classes are always initialized before they are used. The exact timing of atic constructor execution is implementation-dependent, but is subject to the following rules:

• The static constructor for a class is executed before any instance of the class is created.

• The static constructor for a class is executed before any static members of the class are referenced.

• The static constructor for a class executes at most one time during a single program instantiation.

Static Field Initializations

The most common use for a static constructor is to initialize the static fields of a .class. This is because when you initialize a static field directly at its point of declaration, the compiler conceptually converts the initialization into an assignment inside the static constructor. In other words:

 

class Example

{

private static wibble w = new wibble( };

}

is effectively converted by the compiler into

 

class Example

{

static Example( )

{

w = new wibble( );

}

private static wibble w;

}

Static Constructor Restrictions

Understanding the following four restrictions on the syntax of static constructors will help you understand how the common language runtime uses static constructors:

• You cannot call a static constructor.

• You cannot declare a static constructor with an access modifier.

• You cannot declare a static constructor with parameters.

• You cannot use this keyword in a static constructor.

Constructor Overloading

A constructor is the primary method of a class. It allows the programmer to initialize a variable of a class when the class is instantiated. A constructor that plays this role of initializing an instance of a class is also called an instance constructor. Most of the time, you don’t even need to create a constructor, since one is automatically provided to any class you create. Sometimes too, as we have seen in some classes, you need to create your own class as you judge it necessary. And sometimes, a single constructor may not be sufficient. For example, when creating a class, you may decide, or find out, that there must be more than one way for a user to initialize a variable.

Like any other method, a constructor can be overloaded. In other words, you can create a class and give it more than one constructor. The same rules used on overloading regular methods also apply to constructors: the different constructors must have different number of arguments or a different type of arguments.

Constructor overloading

 

using·system;

public class Applicant

{

public string FullName;

public string Address;

public string City;

public string State;

public string zIPcode;

public string sex;

public string DateofBirth;

public int weight;

public string Height;

public int Race;

 

II The default constructor, used to initialize an

II Applicant instance without much information

public Applicant()

{

this.FullName = “unknown”;

this.sex = “ungenerated”;

}

II A constructor that ;s passed only one argument public Applicant(string n)

{

this.FullName = n;

}

 

II A constructor with more than one argument

II This type is suitable to completely initialize a variable public Applicant(string n, string s, string dob)

{

this.FullName = n;

this. Sex = s;

this.dateofBirth = dob;

}

}

Public class exercise

{

Static applicant registerpersonalinformation()

{

string name;

char sex;

string gender = null;

string dob;

 

console.writeLine(” ** Motor vehicle Administration **”);

console.writeLine(“Applicant”s Registration”);

console.write(“Full Name: “);

name = console.ReadLine();

do

{

console.write(“sex(F=Female/M=Male): “);

sex = char.parse(console.ReadLine());

 

if( (sex != If’) && (sex != ‘F’) && (sex != ‘m’)

&& (sex != ‘M’) )

console.writeLine(“please enter a valid character”);

}while( (sex != If’) && (sex != ‘F’) &&

(sex != ‘m’) && (sex != ‘M’) );

if( (sex == If’) I I sex == ‘F’ )

gender = “Female”;

else if( (sex == ‘m’) I I (sex == ‘M’) )

gender = “Male”;

console.write(“date of Birth(mm/dd/yyyy): “);

dob = console.ReadLine();

Applicant person = new Applicant(name, gender, dob);

return person;

}

static void ShOW(Applicant person)

{

console.writeLine (“\n ** Motor vehicle Administration **”);

console.writeLine (” – Applicant’s personal Information -“);

 

console.writeLine(“Full Name: {0}”, person.FullName);

console.writeLine(“Sex: {0}”, person.sex);

console.writeLine(“Date of Birth: {0}\n”, person.DateOfBirth);

}

public static int Main()

{

Applicant App = new Applicant();

App = RegisterPersonalInformation();

ShOW(App);

return 0;

}

}

 

OUTPUT:

 

** Motor Vehicle Administration **

Applicant’s Registration

Full Name: S.K. Kataria

Sex(F=Female/M=Male): d

Please enter a valid character

Sex(F=Female/M=Male): M

Date of Birth(mm/dd/yyyy): 06/10/1972

 

** Motor Vehicle Administration **

 

– Applicant’s Personal Information —

Full Name: Dominique Monay

Sex: Male

Date of Birth: 06/10/1972

Destructor

Destructor is just opposite to the constructor, it destruct the memory of object allocated by constructor.

While a constructor is a method used to initialize an instance of a class, a destructor is used to destruct an instance of class when that variable is not used anymore. Like the constructor, the destructor has the same name as the class. To indicate that the method is a destructor, its name is preceded with a tilde symbol.

 

• A class can only have one destructor.

• Destructors cannot be inherited or overloaded.

• Destructors cannot be called. They are invoked automatically.

Here is an example of a destructor in a class:

 

Sample of destructor

 

using System;

class sampleclass

{

II Constructor

public sampleclass()

{

console.writeLine(“sampleclass – Constructor”);

}

~sampleClass()

{

console.writeLine(“Destructor of sampleclass”);

}

}

public class Newproject

{

static void Main()

{

sampleclass sample = new sampleClass();

console.writeLine(“welcome”);

}

}

 

OUTPUT:

 

SampleClass-Constructor

Welcome

Destructor of SampleClass

 

Like a (default) constructor, a destructor is automatically created for your class but you can also create it if you want. A class can have only one destructor. If you don’t create it, the compiler would create it for your class. If you create it, the compiler would not create another. A destructor cannot have an access level. A destructor is called when the memory that a class was used is no longer needed. This is done automatically by the compiler. For this reason, you will hardly need to create a destructor, since its job is automatically taken care of behind .the scenes by the compiler.

Classes and Object in C#

By Dinesh Thakur

One can create new reference types by defining classes. Classes provide templates’ from which these direct instances are generated. Where we appeal to the relation between a class and its corresponding reference type instances we shall say that a class specifies the type (also that the class specifies the constitutive elements of the type)

 

Any type is made up of elements, which we term type members. There are two main kinds of type members that a class can specify. Firstly, a class can specify other types- both value and reference. This idea, that types can contain other types, is known within the literature on object orientation as ‘containment’, or else ‘aggregation’. Where a type contains another reference type, we shall call it the containing type of the latter.

The second, main kind· of type members that a class can specify are methods, functions designed for reading and manipulating the value and reference types an instance contains.

                           The second, main kind of type members that a class can specify are methods, functions designed for reading and manipulating the value and reference types an instance contains.

Objects in C# are created from types, just like a variable. This type of an object is known as class. we can use class definition to instantiate objects, which means to create a real named instance of a class.

Declaration of Classes

Class is an user-defined data type. To create a class, you start with the class keyword followed by a name and its body delimited by curly brackets. The following is an example of a very simple class declaration

 

class classname

{

// class-body

}

The class-body contains the member data and member function of the class. C++ programmer must note that there is no semicolon after the closing brace of the class.

Members of Class

Class is a mechanism to implement the encapsulation, it bind the data and a function in a single unit. Therefore data and functions are the members of class, which is known as member data and member function.

There is an example of full class:

 

class circle

{

double radius;

public void get_radius(double r)

{

radius = r;

}

public double area()

{

return ( 3.14 * r * r);

}

}

Member Access Modifiers

Access modifiers provide the accessibility control for the members of classes to outside the class. They also provide the concept of data hiding. There are five member access modifiers provided by the C# Language.

                              Access modifiers provide the accessibility control for the members of classes to outside the class.

By default all members of class have private accessibility. If we want a member to have any other accessibility, then we must specify a suitable access modifier to it individually.

For Example:

class Demo

{

public int a;

interna1 int x;

protected double d;

float m; // private by default

}

We cannot declare more than one member data or member function under an accessibility modifier.

Read Only Member

When creating a member variable of a class, one of the decisions you make consists of deciding how the field would get its value(s). Sometimes you will allow the clients of the class to change the values of the field. In some other cases, you may want the field to only hold or present the value without being able to change it. This can still allow the clients to access the field and its value but on a read-only basis.

To create a field whose value can only be read, precede its data type, during declaration, – with the readonly keyword. Here is an example:

 

Public readonly double PI;

After declaring the variable, you should initialize it. You have two main alternatives. You can initialize the field when declaring it. Here is an example:

The use of read only members.

 

using System;

namespace Geometry

{

class circle

{

public double Radius;

public circle(double rad)

{

Radius = rad;

}  

Public readonly double pi = 3.14159

}

class Exercise

{

static int Main()

{

Circle circ = new Circle(24.72);

Console.writeline(“circle characteristics”);

Console.writeline(“radius: {0}”, circ.radius);

Console.writeline(“pi: {0}\n”,circ.pi);

Return 0;

}

}

}

OUTPUT:

 

circle Characteristics

Radius: 24.72

PI: 3.14159

Object creation

In C# objects are created using the new keyword. Actually new is an operator, creates an object of the specified class and returns a reference to that object. Here is an example :

 

public class Exercise

{

public void welcome()

{

Console.writeLine(“This is Exercise class”);

}

}

public class classl

{

static void Main()

{

Exercise exo = new Exercise ();

}

Object-Oriented programming in C#

By Dinesh Thakur

Object-Oriented programming emphasis on data rather than function.

Object-Oriented programming was developed due to the limitations of the traditional programming approaches. The traditional programming approaches, such as Pascal, C, BASIC, FORTRAN and etc., are basically called procedural-oriented programming languages.

Procedural-oriented programming basically emphasis on writing a list of instructions to tell the computer to do something: Get some input, add these numbers, divide by 6, display that output. The programs are dividend into a small subprogram know as a function. Most of functions share global data, if program is too large it is very difficult to identify what data is used by which function. It does not model real world problem, and new enhancement is not easy, whole will be changed or new will be develop.

Object-Oriented Programming emphasis on data rather than function. It divides programs into objects, and they can communicate with each other. It provides the concept to hide the data from the external function and program. New data and functions can be easily added rever necessary. Some fundamental features of Object-Oriented programming are:

.” Concept

Elements of Object-Oriented programming

 

» Member data

A member data is a data hold by an entity (or object).

» Methods

A method is an operation on the member data. Also known as member function.

» Objects

An Object is a real world entity, combine the data and member function in a single unit.

» Classes

Class is a set of similar types of objects.

 

Characteristics of Object-Oriented Programming

 

» Encapsulation

Encapsulation is a mechanism of binding the member data and member function in a single unit.

» Data Abstraction

Data abstraction is mechanism to provide the. Essential feature without describing the background details. Means providing the func1ions to access the hidden (private) data.

» Inheritance

Inheritance is a mechanism of sharing the member data and member function among the classes.

» Polymorphism

Polymorphism is a property to share a single item (or name) in more than one form. (such as function overloading, operator overloading, virtual functions)

What is Structure in C#

By Dinesh Thakur

Structure is a user-defined value type which encapsulates member data and member function.

A struct is a user-defined value type. It is declared in a very similar way to a class, except that it can’t inherit from any class, nor can any class inherit from it (as mentioned\ previously, however, all value types do inherit from System.object), The following example shows a partial declaration for a ‘Coordinate’ struch.

struct Coordinate

{

pub1i c int x;

public int y;

public Coordinate(int x, int y)

{

this . x = x;

this.y = y;

}

}

 

Given the above, one could initialise a Coordinate type in a familiar way, using code like:

 

coordinate c = new coordinate(10, 2);

~ Concept

Note that if a variable of a struct type is declared without being given an explicit value, eg:

 

Coordinate c2 ;

 

it does not equate to ‘null’ (this being the default value for reference types, rather than value types. Instead, the variable is initialised to a state where its fields have their default values.If these fields are basic value types, they will generally be set to zero. If these field they will be set to ‘null’.

 

Because of this default initialization behaviour, it is an error for a struct to be given a parameterless constructor (eg. one like ‘public Coordinate().) Also, where a struct does have a constructor, you should be sure to make assignments to all of the struct’s fields within this constructor.

 

Use of structure

 

using system;

public struct Storeitem

{

public long ItemNumber;

public string ItemName;

public double unitprice;

 

public void DisplayAnltem()

{

console.writeLine(“Department store”);

console.writeLine(“Item #: {0}”, this.ltemNumber);

console.writeLine(“Description: {0}”, this.ItemName);

Console.writeLine(“unit price: {0:C}\n”, this.unitprice);

}

}

public class Exercise

{

static void Main()

{

Storeltem item = new Storeltem ();

 

item.ltemNumber = 348649;

item.ItemName = “Men 3-piece Jacket”;

item.unitprice = 275.95;

 

item.DisplayAnltem ();

}

}

 

OUTPUT:

 

Department Store

Item #: 348649

Description: Men 3-piece Jacket

unit price: 275.95

What is enumeration in C#

By Dinesh Thakur

An enumeration is a special set of numeric type string literals which considered as a constants.

An enumeration is a special kind of value type limited to a restricted and unchangeable set of numerical values. By default, these numerical values are integers, but they can also be longs, bytes, etc. (any numerical/value except char) as will be illustrated below.

When you define an enumeration you provide literals which are then used as constants for their corresponding values. The following code shows an example of such a definition:

 

public enum DAYS

{

Monday,

Tuesday,

Wednesday,

Thursday,

Friday,

Saturday,

Sunday

}

 

Note, however, that there are no numerical values specified in the above. Instead, the numerical values are set up according to the following two rules:

 

1. For the first literal: if it is unassigned, set its value to O.

2. For any other literal: if it is unassigned, then set its value to one greater than the value of the preceding literal.

 

From these two rules, it can be seen that DAYS.Monday will be set to 0, and the values increased until DAYS.Sunday is set to 6. Note also how we are referring to these values – the values specified in an enumeration are static, so we have to refer to them in code using the name of the enumeration: “DAYS.Monday” rather than just “Monday”. Furthermore, these values are final-you can’t change their runtime value.

~

The following code demonstrates how you can override the default setting which makes the default values integers. In this example, the enumeration values are set to bytes.

 

enum byteEnum : byte

{

A,

B

}

 

You can also override the default numerical values of any and all of the enumeration elements. In the following example, the first literal is set to value 1. The other literals are then set up according to the second rule given above, so DAYS.Sunday will end up equal to 7.

 

public enum DAYS

{

Monday=!,

Tuesday,

wednesday,

Thursday,

Friday,

saturday,

Sunday,

}

 

In the two examples given, the values of each literal has been’ unique within the enumeration. This is usually how you will want things to be, but in fact the values need not be unique. In the following case, the value of DAYS.Thursday is also set to equal!. The values assigned to the other literals will follow the rules given previously, so both DAYS.Tuesday and DAYS.Friday will equal 2, etc.

public enum DAYS

{

Monday=l,

Tuesday,

wednesday,

Thursday=l,

Friday,

Saturday,

Sunday

}

In C# enumerations are type-safe, by which we mean that the compiler will do its best to stop you assigning implicit values to enumeration typed variables. For instance, the following code should not compile:

 

int i = DAYS.Monday;

DAYS d = i;

In order to get this code to compile, you would have to make explicit casts both ways (even converting from DAYS to int), ie:

 

int i = (int)DAYS.Monday;

DAYS d = (DAYS)i;

At this point you may be wondering what happens if you cast an int to an enumeration value where that same value is defined for two elements within the enumeration. And the answer is this: one of the elements is given ‘primary’ status, so it gets picked ahead of the other.

A useful feature of enumerations is that one can retrieve the literal as a string from the numeric constant with which it· is associated. In fact, this is given by the default To String() method, so the following expression comes out as true:

DAYS.Monday. ToStringO==”Monday”

The following code prints out both the literal and its constant value for the specified enumeration.

 

Example of Enumeration

 

class EnumTest

{

public enum DAys:byte {MON,TUE, WED,THU,FRI,SAT,SUN}

public static void Main(string[] args)

{

DAYS d=EnumTest.DAYS.SAT;

byte a=(byte) EnumTest.DAYS.SAT;

string str=EnumTest. DAYS. SAT.ToString() ;

consol e. writeline(“{O}, {I}, {2}” ,d, d. ToString() ,d. Tostring(“d”)) ;

consol e. writeline(“{O}, {l}”,str, a) ;

}

}

 

OUTPUT:

SAT, SAT, 5

SAT, 5

Since it’s not immediately obvious what’s going on in the main method here, let’s take the time to go through it.

console.Writeline(“{0}, {I}, {2}” ,d, d. ToString() ,d. Tostring(“d”)) ;

And what the String.Format method does is to take ‘textual representations’ of the objects it is passed as parameters, and slots them into the appropriate places within the ‘format string’ it is passed.

Now, we’ve already noted that ToString () will return a literal string, but what about the method d.ToString (“d”)?

The ToString method can take a single IFormatProvider parameter which indicates how the string conversion should be conducted. Values for this parameter can include things like “g”, “d”, “x”, “f’, etc. The stated implication of “d”, however, is to render in ‘Decimal format’.And when we use this on an enumeration member, it provides a string representation of the “numerical value” of the enumeration member.

Type of String in C#

By Dinesh Thakur

A string is an empty space, a character, a word, or a group of words.

A string is an empty space, a character, a word, or a group of words that you want the compiler to consider “as is”, that is, not to pay too much attention to what the string is made of, unless you explicitly ask it to. This means that, in the strict sense, you can put in a string anything you want.

Primarily, the value of a string starts with a double quote and ends with a double-quote.

An example of a string is “Welcome to the World of C# Programming!”. You can include such a string in the Console.Write () method to display it on the console. Here is an example:

Simple string

using System;

class Bookclub

{

static void Main()

{

console.writeline(“welcome to the world of c# programming!”) ;

}

}

OUTPUT:

welcome to the world of c# programming!

Sometimes, you will need to use a string whose value is not known in advance. Therefore, you can first declare a string variable. To do this, use the string keyword (in fact, it is a class) followed by a name for the variable. The name will follow the rules we defined above. An example of a string declaration is:

string Msg;

After declaring a string, you can give it a primary value by assigning it an empty space, a character, a symbol, a word, or a group of words. The value given to a string must be included in double-quotes. Here are examples of string variables declared and initialized:

string Empty = “”;

string Gender = “F”;

string FName = “Mahatama Gandhi”;

string Msg = “welcome to the world of c# programming! “;

After initializing a string variable, you can use its name in any valid operation or expression. For example, you can display its value on the console using the Console.Write () or the Console.WriteLine () methods. Here is an example:

Use of string variable

using system;

class Bookclub

{

static void Main()

{

string Msg = “welcome to the world of C# programming! “;

console.writeLine(Msg);

 

}

}

 

OUTPUT:

Welcome to the World of C# Programming!

There are two types of string in C#:

1. Immutable strings

2. Mutable strings

The immutable strings are can’t be modify while mutable strings are modifiable.C# also supports a feature of regular expression that can be used for complex strings manipulations and pattern matching.

                          The immutable strings are can't be modify while mutable strings are modifiable.

Handling of Strings

We can create immutable strings using string or String objects in a number of ways.

There are some techniques to handling the immutable strings:

Assigning String

string s1;

s1 = “welcome”;

 

or

string s1 =”welcome”;

Copying String

string s2 = s1;

or

 

string s2 = string.copy(s1);

Concatenating Strings

string s3 =s1 + s2;

 

or

 

string s3 = string.Concat(sl,s2);

Reading from Console

string sl = console.ReadLine(); .

Converting Number to String

int num = 100 ;

string s1= num.Tostring();

Inserting String

string s1 = “wel”

string s2 = s1.Insert(3,”come”);

II s2 = welcome

string s3 = s1.Insert(3,”don”);

/ / s3 = we1don;

Comparing Strings

int n = string.Compare(sl,s2);

This statement will perform case-sensitive comparison and returns integer values for different conditions. Such as:

• If sl is equal to s2 it will return zero.

• If sl is greater than s2 it will return positive integer (1).

• If sl is less than s2 it will return negative integer(-l).

Or you can use following statement:

 

bool a = s2.Equals(sl);

bool b = string.Equal(sl,s2);

Above statements will return a Boolean value true (if equal) or false (if not equal).

Or you can also use the “==” operator for comparing the strings. Like as:

 

if (s1 == s2)

console.write (” both are equal”);

In this statement, it will return a Boolean value true (if equal) or false (if not equal

Mutable String

Mutable strings are those strings, which can be modifying dynamically. This type of strings are created using StringBuilder class. For Example:

 

StringBuilder sl = new StringBuilder (“welcome”);

StringBuilder s2 = new StringBuilder ( );

The string sl is created with an initial size of seven characters and s2 is created as an empty string. They can grow dynamically as more character added to them. Mutual string are also referred as a dynamic strings. Mutable string can be modify dynamically.

The StringBuilder class supports many methods that are useful for manipulating dynamic strings. Some of the most common methods are listed below:

                       Some of the most common methods

StringBuilder also provides some attributes to access some properties of strings, such as:

                        StringBuilder also provides some attributes to access some properties of strings

Here is an example program for mutable string. To use string builder class we have to use System. Text in the program.

Mutable string

using system.Text;        // For using StringBuilder

using system;

class strMethod

{

public static void Main( )

{

StringBuilder s = new stringBui1der(“c”};

console.writeLine(” stored string is :”+ s);

console.writeLine(“Length of string is :”+s.Length);

 

s.Append(“Sharp “);   II appending the string s

 

Console.writeLine(“After Append String is :”+ s);

console.writeLine(“Length of string is :”+s.Length);

//space will be count in “sharp” string.

 

s.Insert(7,”Language”); II inserting the string at last in s

 

console.writeLine(“After Insertion String is:”+ s);

console.writeLine(“Length of string is :”+s.Length);

 

int n = s.Length;

 

s [n] = “!”;

console.writeLine (” At Last String is:”+ s);

}

}

 

OUTPUT:

 

Stored string is : C

Length of string is 1

After Append string is : cSharp

Length of string is : 7

After Insertion string is : cSharp Language

Length of string is: 15

At Last String is : cSharp Language!

Next Page »

Primary Sidebar

C# Tutorials

C# Tutorials

  • C# - .NET Languages Types
  • C# - Dot Net
  • C# - Dot Net Framework
  • C# - Inheritance Types
  • C# - Features
  • C# - CTS
  • C# - CLS
  • C# - CLR
  • C# - Console
  • C# - MSIL
  • C# - Base Class Library
  • C# - Web Forms Creation
  • C# - C# Vs C++
  • C# - Statements Types
  • C# - JIT
  • C# - CLI
  • C# - Controls Types
  • C# - String Types
  • C# - Execution Model

Other Links

  • C# - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW