KB Controls is reader-supported. When you buy through links on our site, we may earn an affiliate commission. Read more in our disclaimer

Creating an Interactive C# .NET Project in Visual Studio Code

In this part of the series, we learn how to add interactivity to our application. Along the way, we will learn about methods, arrays, and string manipulation in C#.

Welcome to another edition of C# From Scratch, a course dedicated to teaching you everything you need to know to be productive with C#. If you’re new here, head over to the index to see all parts of the series.

In previous parts of the series, we have seen how to create C# .NET projects using the .NET CLI, how to run C# projects using the .NET CLI, and how to edit code using Visual Studio Code. This is a great start for learning how to work with C# but the application that we have worked with so far has a major limitation - the output is hardcoded. Most useful applications are interactive - the output of the application changes based on the input provided by a user.

In this part of the series, we will focus on extending our application to make it interactive. By the end of this post, our application will output a personalized greeting based on the input provided by a user. Along the way, we'll learn some concepts about the C# language as well as C# syntax and data types.

Let's start by taking a closer look at the code that already makes up our static application.

The Main Method

The Main Method

Lines 7 - 10 of the Program.cs file is what is known as a method definition.

A method is a named container for code. In this case, the name of the method is Main.

All of the code belonging to a method is wrapped up in curly braces which follow the name of the method. On line 8, you can see the opening curly brace for the method and on line 10, you can see the closing curly brace. All of the code inside these curly braces is part of the method.

When a method is called, or invoked, then the code inside of the method is executed.

You may have noticed the keywords "static" and "void" which come before the name of the method. These keywords define the way the method behaves and we'll talk in detail about what they mean later on in the series.

The Main method is a special method in a .NET Console application. It is special because it is the entry point for the application. When you run a .NET Console application, the .NET Runtime looks for a method called Main and starts executing the application's code from that method.

In this application, there is only one line of code inside of the Main method. This code, located on line 9, tells the .NET Runtime to write a string of characters to the Console window.

WriteLine is a method, just like the Main method. The Console prefix on the method call indicates that this method belongs to the class Console. We'll talk about classes a little bit later on.

Method Parameters and Data Types

Method Parameters

As part of a method definition, you can define what parameters someone can pass to a method. Every method can have zero or more parameters. Parameterization helps to make methods flexible and reusable across many different applications.

In a method definition, the parameter list is defined immediately after the name of the method in parentheses. Each parameter in the parameter list is made up of a data type and a name.

The Main method takes one parameter called args, which is short for arguments. Arguments are the values that are passed into the method when it is called during execution of the program. The args parameter is of type String[]. What does that mean?

First of all, we have to define the type of a parameter because C# is a strongly typed language. That means that every parameter and variable in C# has a defined type. The type of a variable determines how much space in memory a variable occupies, what data can be stored in the variable, and what operations are legal for that variable.

Here, the type of args is a String array. We have already met the String data type in the previous part of the series and we know that a String is a sequence of characters enclosed in double quotes. "Hello" is an example of a String.

A String array is a collection of Strings. ["Hello", "my", "name", "is", "Ken"] is an example of a String array. An array may also contain zero strings, so [] is also an example of a string array. We know that this is an array of a certain data type because of the square brackets that immediately follow the name of the type.

Args is a special parameter because it represents the arguments for the application. Any arguments that a user passes to the application on the Console are available to read in the program through args.

Working with Arrays

To work with arrays, we need to understand how to access specific elements in the array.

In our example, we want to print a personalized greeting based on the first argument passed into the application a by a user. If a user passes more than one name into the application, we print the greeting based on the first argument and discard the rest. So, if the args array contains three strings, how do we access the first string?

In C#, you can access an element of an array based on its position in the array. To access a specific element, you can add the index, or position, of the element in square brackets after the array. C#, like most programming languages, uses zero based indexing. That means that the first element in an array lives at index 0. So, in our example, when we want to access the first string in the array args, we can use the expression args[0]. If you read that expression out loud, you would say "args sub 0".

Working with Strings

In our application, we expect a user to pass in a single argument, which is the name of the person that the application should greet. We know that we can access the argument that the user has passed into the application using the expression args[0].

So, how do we use this argument to print a personalized greeting to the Console?

We have two options; string concatenation and string interpolation. Both are techniques which are used to build strings using a combination of literal stings (hardcoded characters between double quotes) and expressions which resolve to string values. Let's start by looking at string concatenation in C#.

String Concatenation

String concatenation allows us to join small strings of characters together to create a larger string. You can join, or concatenate, strings together using the + operator in C#. So, if we wanted to print the greeting "Hello, <name>!" we could use the expression "Hello, " + args[0] + "!".

String Concatenation

String Interpolation

String concatenation is a perfectly valid way to build strings in C#. However, there are C# developers who argue that string interpolation, another technique for building strings in C#, is easier to read.

To use string interpolation, you must place a dollar sign ($) before the opening double quote of the string. Now, you can place an expression in curly braces anywhere inside the string. This results in easier to read strings which don't have to be stopped and started with pairs of double quotes.

To build our personalized greeting with string interpolation, we could use the expression $"Hello, {args[0]}!".

String Interpolation

In both cases, the expression args[0] will resolve to a value at runtime.

Test the Application

After updating Program.cs, save the file and come back to the Command Prompt. When we run the application, .NET knows that the source code has been modified and will produce a new assembly file by rebuilding the application.

This time, we want to pass an argument to the application when we run it. You can do this by appending two dashes and the argument to the dotnet run command. To pass the argument KB Controls to the application, I would use the command "dotnet run -- KB Controls". These two dashes are required to tell .NET that the arguments are application arguments and not arguments for the .NET CLI.

Before you run the application, make sure that you are in the correct directory. When you run the application, you will see that a personalized greeting is printed to the Console window.

A Personalized Greeting is Output

Wrap Up

In this section, we have built an interactive application that updates its output based on a user's input. While building the application, we have learned some basic concepts about methods, C# syntax, and string manipulation in C#.

After building a new feature like this, its good to test some exceptional situations. After all, software user's are not famous for doing exactly what software developers expect them to do.

What happens if you pass two arguments to the application? Everything should work as normal and the Console output is based on the first argument passed by the user.

What happens if you pass no arguments to the application? That causes a catastrophic failure in the application (also known as an unhandled exception) which causes the application to crash. It seems that our software has a bug, and in the next lesson we will learn how to use Visual Studio Code to debug our code.

Unhandled Exception
PLC Programming Bootcamp

Learn PLC programming and kick start your career as a PLC programmer by following our free 5 day bootcamp.

Learn More

Related Content