Let's get started with a simple C#-based console application. This console application will introduce some basic C# code and get things up and running for the library we are going to build in the next recipe. Our main focus is to get to the C# coding and prepare ourselves for all the excitement we are going to have later.
To step through this recipe, you will need a running copy of Visual Studio 2017 with the latest version of .NET Framework. If you don't have a copy of Visual Studio 2017, you can download it from https://www.visualstudio.com/.
This will take you to Microsoft's Visual Studio website. Follow the instructions on the site to get a copy of Visual Studio and get things started.
- Open Visual Studio 2017.
- Click
File
|New
|Project
and, in theNew Project
template dialog box, selectVisual C#
in the left-hand pane andConsole App (.NET Framework)
in the right-hand pane:
- In the
Name:
text box, type a name for your application. In this case, typeHelloCSharp
. Select a preferred location in theLocation:
drop-down list or click theBrowse...
button and select a location. Leave the defaults as they are:
- Now Click
OK
. - You will be presented with a default code template for a C# console application. Let's hit F5 to give it a test run. If everything is fine, a console will pop up and close.
- At the end of the
Main
method, type the following code snippet:
private static string SayHello(string yourName) { return $"Hello, {yourName}"; }
- Now, inside your
Main
method, type the code that calls the previous method we just created:
var message = SayHello("Fiqri Ismail"); Console.WriteLine(message); Console.ReadLine();
static void Main(string[] args) { var message = SayHello("Fiqri Ismail"); Console.WriteLine(message); Console.ReadLine(); } private static string SayHello(string yourName) { return $"Hello, {yourName}"; }
- Let's hit F5 and test the application. If everything is OK, you should see the following screen. Press Enter to exit:
Let us take a quick look at what we did in the previous recipe. In steps 1 to 4, we created a C#-based console application. The skeleton for a console application already comes with Visual Studio as a template. Giving a proper name to your project and a location is a good habit. These things will help you to track down your project easily for future use. In step 5, we just make sure the default console application template works fine and that there are no surprises waiting for us before doing any actual coding.
In step 6, we created a static method that takes a string
parameter and returns a message with that parameter; this is called String Interpolation. It's a new feature introduced in C# 6.0 and can be used instead of the traditional string.format()
method. Step 7 uses that method inside the main method. As in a normal console application, Console.ReadLine()
will wait till any key is pressed before exiting. Finally, in step 9, we debug the code to check that everything works fine and as expected.