Visual C # .NET Getting Started
Release Date: 6/28/2004
| Update Date: 6/28/2004
Microsoft Corporation
Suitable for: Microsoft Visual C # .NET
Summary: Visual C # .NET is the latest member of the Visual Studio Suite for a powerful programming language. Visual C # .NET Getting Started By implementing a simple QuickSort algorithm, take you to build a Visual C # .NET project.
Download Quicksort_Visual_CSHARP_.NET.EXE.
This page
Introduction Procedure 1. Beginning Project Step 2. Hello, World! Step 3. Program Structure Step 4. Console Input Step 5. Using Array Step 6. File Enter / Output Step 7. Create Functions Step 8. Use the Debugger Summary: Quicksort C # .NET Source Code Record: About Quicksort C # .NET
Introduction
Visual C # .NET is the latest member in the Visual Studio family. This new language is based on C / C , but it deepens the development direction of component-oriented programming. C / C programmers should be very familiar with its grammar.
The following sample application demonstrates how to build a simple C # item for the QuickSort algorithm. It includes the basic components of the C # program: read / write console and files, create functions, and use basic arrays.
These entry guides are not intended to cover all aspects of the programming language. They are just a starting point for you to explore this language. We encourage you to perform in accordance with this tutorial because it includes each of the different parts of the Quicksort application. You can also get a complete source code and project file.
Recommended requirements
Compile this sample application requires Visual Studio.net (beta 2 or higher). Knowledge about C / C is help but not required.
Back to top
Step 1. Start the project
Development work in Visual Studio is organized in the form of a solution, and each solution contains one or more items. In this tutorial, we created a solution contains a C # project.
Create a new project
1. In the Visual Studio .NET environment, select File | New | Project from the menu.
2. Select Visual C # Projects on the left and select Console Application on the right.
3. Specify the name of the project and enter the location of the creation project. Visual Studio automatically creates project directory.
4. Click OK, then it is officially started!
Visual C # Solution
Visual Studio.net has created a solution with a simple Visual C # project. The project contains two files: assemblyinfo.cs and class1.cs.
The next steps will discuss these different files and how to compile the project.
Back to top
Step 2. Hello, World!
Unfortunately, we still can't resist this temptation ... We have to complete a C # classic "Hello, World!" Application, this application was originally written in C language.
Modify source code
1. Double-click "Class1.cs" in Solution Explorer. You can display Solution Explorer through the "View" menu. 2. Change the pre-generated template (Class1.cs), as shown in the following, as shown in the slope. Using system;
Namespace Quicksort
{
///
/// summary description for class1.
///
Class class1 {
Static void main (string [] args)
{
//
// Todo: add code to start application here
//
Console.writeline ("Hello, C # .NET World!");
}
}
}
3. Note that when you type code, Visual Studio will prompt you the name of the class and function (because the .NET framework issues this type of information).
Compile application
1. Since you have completed the modification, you can compile the Visual C # item by simply selecting Build in the Build menu.
2. Errors and messages from C # compilers are displayed in the Output window. If there is no error, you can run the Hello World application by clicking Start WITHOUT DEBUGGING under the Debug menu.
Program output
When running a Hello World sample application in Visual C #, the screenshot of the output result is as follows:
Understanding changes
The WriteLine () function of the System.Console class prints the string passed to it, followed by a new line of characters. This function can accept parameters of many other data types (including integer and floating point).
After the program is loaded, the control is passed to the main () function. This is why we insert the WriteLine () call in this process.
Back to top
Step 3. Program structure
Since we have built a simple Hello World application, let us stop to analyze the basic components of the Visual C # application.
Source code notes
Character // Mark the remainder of the row as a comment, so the C # compiler will ignore it. In addition, the code between / * and * / will also be treated as a comment.
// this line is ignored by the compiler.
/ * This block of text is also
Ignored by The Visual C # compiler. * /
Using instruction
The .NET framework provides developers with many useful classes. For example, the Console class handles the input and output of the console window. These classes are organized in the form of hierarchy trees. The fully qualified name of the Console class is actually System.Console. Other classes include System.IO.FileStream and System.collections.Queue.
The USING command allows you to reference classes in the namespace without using a fully qualified name. The Using Directive is applied with the code that protrudes in the slope body.
Using system;
Class class1
{
Static void main (string [] args)
{
System.console.writeline ("Hello, C # .NET World!");
Console.writeline ("Hello, C # .NET World!");
}
}
Class declaration
Unlike C or Visual Basic, all functions in Visual C # must be packaged in a class. Class statement declares a new C # class. For the Hello World application, the Class1 class contains a function, the main () function. If you use a Namespace block to define the class, you can organize the class to organize a level such as MSDNA.quicksortApp.
In this introductory guide, we don't plan to introduce classes in depth, but we will make a brief overview why the class is part of our sample application.
MAIN () function
After the application is loaded into memory, the main () function receives control, so the application startup code should be placed in this function. The command line parameter passed to the program is stored in the args string array. Back to top
Step 4. Console input
Now we will continue to write Quicksort applications. The first thing we need to do is to prompt users to provide input and output files.
Modify source code
Change the C # source file (Class1.cs), as shown in the code that is slope, as shown below. Other differences (such as class) can be ignored.
// Import namespaces
Using system;
// Declare Namespace
Namespace MSDNAA
{
// Declare Application Class
Class QuicksortApp
{
// Application Initialization
Static void main (String [] Szargs)
{
// Describe Program Function
Console.writeline ("Quicksort C # .NET Sample Application / N");
// Prompt User for FileNames
Console.write ("Source:");
String szsrcfile = console.readline ();
Console.write ("Output:");
String szdestfile = console.readline ();
}
}
}
Read from the console
The READLINE () method of the Console class prompts the user to enter and return the input string. It automatically handles memory allocation for strings, because you use the .NET garbage collector, you don't need to do anything to release memory.
Program output
Select Debug | Start Without Debugging from the menu to run the program. This is a screenshot of the output from the QuickSort application from this to this.
Back to top
Step 5. Use arrays
The program needs to store it into an array before sorting the rows read from the input. We will briefly discuss the usage of the .NET base class that enables an object array.
Modify source code
Change the C # source file (Class1.cs), as shown in the code that is slope, as shown below. Other differences (such as class) can be ignored.
// Import namespaces
Using system;
Using system.collections;
// Declare Namespace
Namespace MSDNAA
{
// Declare Application Class
Class QuicksortApp
{
// Application Initialization
Static void main (String [] Szargs)
{
// Describe Program Function
Console.writeline ("Quicksort C # .NET Sample Application / N");
// Prompt User for FileNames
Console.write ("Source:");
String szsrcfile = console.readline ();
Console.write ("Output:");
String szdestfile = console.readline ();
// Todo: Read Contents of Source File
ArrayList Szcontent () = new arraylist ();
}
}
Use the ArrayList class
We will import system.collections namespace so we can reference ArrayList directly. Such an object of this type to dynamically adjustable. To insert a new element, you can simply pass the object to the ADD () method of the ArrayList class. The new array element will reference the original object, and the garbage collector will process its release.
String szelement = "insert-me";
ArrayList SzaRray = new arraylist ();
Szarray.Add (Szelement);
To retrieve existing elements, pass the index of the desired element to the item () method. In addition, as a simple form, square brackets Operator [] can also be used, which is actually mapped to the Item () method.
Console.writeline (SzaRray [2]);
Console.writeline (SzaRray.Item (2));
There are still many other methods in the ArrayList class, but insert and retrieval are we need to use in this example. Please refer to the MSDN library to get a complete reference guide.
Back to top
Step 6. File input / output
Now let's implement the read input file and write output files. We read each line into a string array and then output the string array. In the next step, we will use the QuickSort algorithm to sort this array.
Modify source code
Change the C # source file (Class1.cs), as shown in the code that is slope, as shown below. Other differences (such as class) can be ignored.
// Import namespaces
Using system;
Using system.collections;
Using system.io;
// Declare Namespace
Namespace MSDNAA
{
// Declare Application Class
Class QuicksortApp
{
// Application Initialization
Static void main (String [] Szargs)
{
... ...
// read Contents of Source File
String szsrcline;
ArrayList Szcontents = New ArrayList ();
FileStream fsinput = new filestream (szsrcfile, filemode.open,
FileAccess.read;
StreamReader Srinput = New StreamReader (fsinput);
While (szsrcline = srinput.readline ())! = null)
{
// append to array
Szcontents.add (szsrcline);
}
SRINPUT.CLOSE ();
fsinput.close ();
// Todo: Pass to Quicksort Function
// Write Sorted Lines
FILESTREAM FSOUTPUT = New FileStream (szdestfile,
Filemode.create, FileAccess.write;
StreamWriter Sroutput = New StreamWriter (fsoutput);
For (int NINDEX = 0; NINDEX // Write Line to Output File SROUTPUT.WRITELINE (SZContents [NINDEX]); } SROUTPUT.CLOSE (); fsoutput.close (); // Report Program Success Console.writeline ("/ NTHE SORTED LINES HAVE BEEN WRITTEN./N"); } } } Read from the source file Use the FILESTREAM class to open the source file, then join the StreamReader class so that we can use its Readline () method. Now, we call the readline () method until it returns NULL, which means that the end of the file is reached. During the loop process, we store the rows in the string, and then close the two objects. Write output file Suppose it has been sorted with Quicksort, the string array is used, and the thing to do will be the content of the output array. In the same way, we attach the StreamWriter object to the FileStream object. This allows us to use the WriteLine () method, which can easily imitate the behavior of the Console class. Once the array is traversed, we can close these two objects as in front. Back to top Step 7. Create a function The final step is to create a function to run Quicksort in the string array. We put this function in the application class QuickSortApp. Modify source code Change the C # source file (Class1.cs), as shown in the code that is slope, as shown below. Other differences (such as class) can be ignored. // Import namespaces Using system; Using system.collections; Using system.io; // Declare Namespace Namespace MSDNAA { // Declare Application Class Class QuicksortApp { // Application Initialization Static void main (String [] Szargs) { ... ... // pass to quicksort function Quicksort (szcontents, 0, szcontents.count - 1); ... ... } // Quicksort Implementation Static Void Quicksort (ArrayList Szarray, int nlower, int Nupper) { // Check for non-base case IF (NLOWER { // split and sort partitions Int nsplit = partition (SzaRray, NLower, Nupper); Quicksort (SzaRray, NLower, NSPLIT - 1); Quicksort (SzaRray, NSPLIT 1, Nupper); } } // Quicksort Partition IMPLEmentation Static Int Partition (ArrayList Szarray, Int nlower, int Nupper) { // pivot with first element INT NLEFT = NLOWER 1; String szpivot = (string) SzaRray [NLOWER]; int NRight = Nupper; // Partition Array Elements String szswap; While (NLEFT <= NRIGHT) { // Find Item Out of Place While (NLEFT <= NRIGHT) { IF ((String) SzaRray [NLEFT]). Compareto (Szpivot)> 0) Break; NLEFT = NLEFT 1; } While (NLEFT <= NRIGHT) { IF ((String) SzaRray [NRIGHT]). Compareto (Szpivot) <= 0) Break; NRIGHT = NRIGHT - 1; } // Swap Values if Necessary IF (NLEFT { Szswap = (string) SzaRray [NLEFT]; SzaRray [NLEFT] = SzArray [NRIGHT]; SzaRray [NRIGHT] = SZSWAP; NLEFT = NLEFT 1; NRIGHT = NRIGHT - 1; } } // Move Pivot Element Szswap = (string) SzaRray [nLower]; SzaRray [nlower] = SzArray [NRIGHT]; SzaRray [NRIGHT] = SZSWAP; Return nRight; } } } Quicksort () function This function requires three parameters: the reference, the lower bound, and the upper bound of array. It calls the partition () function to divide the array into two parts, some of which contain all the strings before the Pivot value, and the other part contains all strings after the Pivot value. It then calls itself to sort each part. The comments in the above modification should indicate the role of each code block. The only new concept is the use of the CompareTo () method, which is a member of the String class, and should be inspeir. Run Quicksort application This step completes the Quicksort C # sample application. Now you can build a project and run an application. A sample text file is required for sorting it. Put this file in the same directory as the EXE file. Program output Here is the output of the completed Quicksort C # .NET sample application. You can view the sample input file 'example.txt' and the output file 'output.txt'. Back to top Step 8. Using the debugger The debugger is an essential tool for diagnostic procedures. We feel that it is necessary to introduce it in this guide. This last step will show you how to take out procedures and use features such as QuickWatch. Set breakpoint When the program runs in the debugger, the breakpoint will suspend the execution of the program, so that the developer can control the debugger. To set a breakpoint, right-click the row you want to suspend, then click InsertBreakPoint, as shown below. Note: Rows with breakpoints are highlighted in red. Click on the row again and select Remove BreakPoint to delete the breakpoint. Single-step debugger Since the breakpoint is set (preferably in the row shown in the previous, let us run the program in the debugger. In the debug menu, select START instead of choosing Start WITHOUT DEBUGGING. This initiates the program in the debugger and thus activates the breakpoint. Once the program encounters breakpoints, the debugger will receive the control of the program. At this time, there will be an arrow to point to the current executed. To order a line of code, you can choose Debug | Step over and observe whether the cursor moves to the next line. The debug | step INTO command allows you to perform a function that will be called. The screen after the two Step over is made is as follows. If you want a program to continue to execute before you encounter an exception or exit, select Debug | Continue from the menu. Check the variable value When you can control the debugger, move the mouse pointer to the variable to get the basic value. You can also right-click the variable and select QuickWatch from the context menu. QuickWatch will provide you with more details about certain variables (such as ArrayList objects). Other debugger tools The Visual Studio debugger features a number of other tools (such as the Call Stack Viewer), you can use this debugger to view the functions called this. You can also get memory dumps and information about threads in the process. We encourage you to use these powerful debugging tools. Back to top summary This entry guide is intended to help you build a simple C # item with Visual Studio. It cannot be a comprehensive introduction. We encourage you to check with other resources of C # and .NET to learn more of these technologies more. After completing this tutorial, you have at least one available item, you can start from modifying this code when you study Visual C #. For convenience, we provide a complete source of source and project files. You can access them through the directory at the top of this document. Other resources We strongly recommend the following books about the C # and .NET platforms. They are the beneficial resources of developers trying to learn these new technologies. • Archer, Tom.inside C # .redmond: Microsoft Press, 2001. • Deitel, Harvey.c #: How To Program.upper Saddle River, NJ: Prentice Hall, 2001. • Gunnerson, Eric.a Programmer's Introduction To C # .new York : Apress, 2000. • Platt, David.Introducing Microsoft .NET.REDmond: Microsoft Press, 2001. Back to top Pixabay: Quicksort C # .NET source code Below is a complete source code for the Quicksort C # .NET sample application. You can copy, use, and distribute these code (no copyright fee). Note that these source code are provided with "as" as "as" // // Quicksort C # .NET Sample Application // Copyright 2001-2002 Microsoft Corporation. All Rights Reserved. // // msdn academic alliance [http://www.msdn.microsoft.com/academic] // this Sample Is Part of a Vast Collection of Resources We develop for // Faculty MEMBERS IN K-12 And Higher Education. Visit The MSDN AA Web Site for more! // the source code is provided "as is" without warranty.// // Import namespaces Using system; Using system.collections; Using system.io; // Declare Namespace Namespace MSDNAA { // Declare Application Class Class QuicksortApp { // Application Initialization Static void main (String [] Szargs) { // Print Startup Banner Console.WriteLine ("/ NQUICKSORT C # .NET Sample Application"); Console.writeline ("Copyright (C) 2001-2002 Microsoft Corporation. All Rights Reserved./N"); Console.writeline ("MSDN Academic Alliance"); // Describe Program Function Console.Writeline ("this Example Demonstrates the Quicksort Algorithm by Reading An Input File,"); Console.writeline ("Sorting ITS Contents, And Writing Them To a New File./N"); // Prompt User for FileNames Console.write ("Source:"); String szsrcfile = console.readline (); Console.write ("Output:"); String szdestfile = console.readline (); // read Contents of Source File String szsrcline; ArrayList Szcontents = New ArrayList (); FILESTREAM FSINPUT = New FileStream (Szsrcfile, Filemode.Open, FileAccess.read); StreamReader Srinput = New StreamReader (fsinput); While (szsrcline = srinput.readline ())! = null) { // append to array Szcontents.add (szsrcline); } SRINPUT.CLOSE (); fsinput.close (); // pass to quicksort function Quicksort (szcontents, 0, szcontents.count - 1); // Write Sorted Lines FileStream Fsoutput = New FileStream (Szdestfile, Filemode.create, FileAccess.write); StreamWriter Sroutput = New StreamWriter (fsoutput); For (int NINDEX = 0; NINDEX { // Write Line to Output FilesRoutput.writeLine (Szcontents [NINDEX]); } SROUTPUT.CLOSE (); fsoutput.close (); // Report Program Success Console.writeline ("/ NTHE SORTED LINES HAVE./N"); } // Quicksort Implementation Private Static Void Quicksort (ArrayList Szarray, Int nlower, int Nupper) { // Check for non-base case IF (NLOWER { // split and sort partitions Int nsplit = partition (SzaRray, NLower, Nupper); Quicksort (SzaRray, NLower, NSPLIT - 1); Quicksort (SzaRray, NSPLIT 1, Nupper); } } // Quicksort Partition IMPLEmentation Private Static Int Partition (ArrayList Szarray, Int Nlower, int Nupper) { // pivot with first element INT NLEFT = NLOWER 1; String szpivot = (string) SzaRray [NLower]; INT NRIGHT = NUPPER; // Partition Array Elements String szswap; While (NLEFT <= NRIGHT) { // Find Item Out of Place While (NLEFT <= NRIGHT && ((String) SzaRray [NLEFT]). Compareto (Szpivot) <= 0) NLEFT = NLEFT 1; While (NLEFT <= NRIGHT && ((String) SzaRray [NRIGHT]). Compareto (Szpivot)> 0) NRIGHT = NRIGHT - 1; // Swap Values if Necessary IF (NLEFT { Szswap = (string) SzaRray [NLEFT]; SzaRray [NLEFT] = SzArray [NRIGHT]; SzaRray [NRIGHT] = SZSWAP; NLEFT = NLEFT 1; NRIGHT = NRIGHT - 1; } } // Move Pivot Element Szswap = (string) SzaRray [nLower]; SzaRray [nlower] = SzArray [NRIGHT]; SzaRray [NRIGHT] = SZSWAP; Return nRight; } } } Back to top Record: About Quicksort C # .NET To demonstrate how the Quicksort Visual C # .NET sample application is actually run, we provide compiled executables. You can create your own executable by compiling these project files. Click QuickSort_visual_csharp_.net.exe, download the source code project file and the executable package. Using an application Start Command Prompt (From the Start "menu, run" cmd.exe "). Use the CD command to change the directory to the directory where the executable is located. Then run "Quicksort.exe". The program will prompt you to provide the name of the input and output file. Any text file containing multiple lines can be used. You can use a notepad to create such files if needed. The program then sorts the contents of the input file and writes it to the output file. Example program output Below is the output from an instance of this QuickSort C # .NET application. This example demonstrates the Quicksort algorithm, and the method is to read the input file, sort the contents of the file, and write it to a new file. The text entered by the user is overlined. You can view the following example input file 'example.txt' and output file 'output.txt'. Quicksort C # .NET SAMPLE APPLICATION Copyright (C) 2001-2002 Microsoft Corporation. All Rights Reserved. MSDN Academic Alliance [http://www.msdn.microsoft.com/academic] This Example Demonstrates The Quicksort Algorithm by Reading An Input File, Sorting its contents, and Writing Them to a new file. Source: Example.txt Output: Output.txt The Sorted Lines Have Been Written to The Output File. View the example input file "eXample.txt": Visual C # Windows Embedded JavaScript SPEECH API ASP.NET VBScript Windows Media Visual Basic .NET Framework BizTalk Server XML Parser Internet Explorer Visual C # SQL Server Windows XP DirectX API View the sample output file "Output.txt": .NET Framework ASP.NET BizTalk Server DirectX API Internet Explorer JavaScript SPEECH API SQL Server VBScript Visual Basic Visual C # Visual C # Windows Embedded Windows Media Windows XP XML Parser Go to the original English page