Introduction

It’s like an old tradition to introduce new programming language to the readers using a ‘Hello World!’ program, so keeping that in mind here are the steps to create your first Hello World program in C# and a step by step explanation of each line and keyword used in the program. We also have some examples where we would be consuming C# code in PowerShell and executing it. This approach makes it easy for the reader to understand both these languages and also use them together.

If you like reading this article follow me on Twitter @singhprateik, for more such content!


Table of Contents


[Announcement] PowerShell to C# and back Book

This book bridges concept and knowledge the gap between a scripting language like PowerShell and modern programming language like C#, which is a natural language of choice for People who know PowerShell.

An increase in adoption of software development inside Infrastructure teams makes this the perfect time to get started with a programming language and C# is a natural choice for people using PowerShell today. As it fits best with the basket of matching skillsets like Azure, Azure DevOps which will add value in your career

Download the FREE Book Sample from the book web page which covers all the basics of C# within 50 pages – https://leanpub.com/powershell-to-csharp 👇 👇 👇


Creating a Hello World Program

A C# program consists of one or more source code files, that contains classes, methods, properties separated in namespaces and when the C# program is compiled, then these are packaged into assemblies with extension .exe for applications and .dll for libraries.

Before we can start that, it is a prerequisite to download and install the .NET Core SDK . Once that is done, then to create a basic console application using .Net Core simply run the following command from PowerShell or Windows Command prompt:

dotnet new console --output app

This will create a new console application project and scaffold a folder named: app with the bare minimum files required. One important file created in this folder is program.cs where .cs extension refers to the C# Hello Program or source code file.


Running the Program

We can go ahead and run the program using the dotnet run command, which is a convenient way to run your application source code from the command line, make sure you are in the application directory when you are running this command. The dotnet run can automatically build the project if necessary, but you can also explicitly build the project using the command: dotnet build that builds but doesn’t run the program.

dotnet run
dotnet build

The dotnet build command converts all the project source code, references, and dependencies into an intermediate language (IL) with extension .dll and depending upon the type of project and the settings\properties in the project file: <project name>.csproj other files like executable .exe will be included in the project build.

All the output file on the build will be written by default to the location:
<project name>\bin\<configuration>\<target>


Line by Line Explanation of Hello World Program

The purpose of this Hello world program is to help you understand the basic syntax and requirements of a C# program. So, let’s try to understand everything in this program, by breaking it line by line:

using System; 

The using directive is used to call class libraries that are required to execute the project. Here System is the class library, that is required to call the Console.WriteLine() method in the Hello world program.  A program can have multiple using statements if required like in the following example:


using System.Console;
using System.Math;

Just like we have System class library we can also create custom class libraries like ’app’ using the namespace keyword, which helps to organize our classes. In simpler words, a  Namespace is a collection of classes, like in the above example, the app namespace contains the class Program.

Similarly, we can create more namespaces using the namespace keyword, like in the following example we created a Parent namespace, with a Child class, but we need to call it at the top using the using directive so that we can qualify the Child class in the Main() method and instantiate it.

 


Access Modifier

In the Hello World example, you won’t see an access modifier before the class keyword, and when access modifier is not specified, then by default it is internal for a class and you can also explicitly specify public or internal access if required. As a thumb rule, a minimum possible access is granted by default, read more about C# access modifiers here to understand better.

Let’s create a C# program with a default class access modifier and try to access that in PowerShell. When I tried to add the type using Add-Type PowerShell cmdlet, it gave us a warning “The generated type is not public” which means you can not instantiate it, because it is not publically accessible outside the C# program. Hence you see that error at the end of the screenshot, yelling at us that “Cannot find the type”

Now if we add public access modifier and then we can not only instantiate the class because it is publically available, but we can also access the public method Main() as demonstrated in the following example:


class Program

A class is a blueprint or template that helps define a type. A class has a name like ’Program’ and can contain variables, methods, and other types. You can not create a C# program without a class definition, it is mandatory!


static

This is a special keyword, and when it is used with a method then the method can be called or accessed directly without creating an instance of the class in which it is defined. There is no difference in a static class or a non-static class, except you cannot use the new operator to create an object of static class and later assign it to a variable. Instead, static class members can be accessed directly using the name of the class.

In the following example, we can call the static Main method without instantiating the Program class:

Get-Content .\Program.cs
$typedef = Get-Content .\Program.cs | Out-String
Add-Type -TypeDefinition $typedef -Language CSharp

In PowerShell, you can also access the static members of a class using :: an operator which is also known as the static member operator as shown in the above example. To view the static members once the object has been instantiated pipe the object to the Get-Member cmdlet and use the -Static switch parameter as highlighted in the following example:


void

It is a return type of the method which means that the method doesn’t return any value. Main can either have a void or int return type. You have already seen the use case with void, let see one more example by changing the return type from void to int.

But if you run the program you won’t see any integer returned from Main() method. To access the integer returned from the Main() method in PowerShell we can use the $LASTEXITCODE which represents the exit code or error level of the last script/application executed, as shown in the following example:


Main()

This is the entry point of the program that means in a console application, the first statement in the Main() method is the starting point of the program. The Main() method must be declared inside a class and must be static. The string[] parameter in the Main() method is optional and we will look into its u purpose and the use cases in the following sub-section.

NOTE Only console or a windows application require an entry point, that means Libraries and services can live without a Main() method.

Following is a list of valid Main() method signatures that can be used in a C# program

<Access Modifier> static void Main() { }
<Access Modifier> static int Main() { }
<Access Modifier> static void Main(string[] args) { }
<Access Modifier> static int Main(string[] args) { }

More than that we can also use, Asynchronous programming using Async and await with the following method signatures, where return type: Task represents an asynchronous task operation and Task<int> represents an asynchronous operation that can return a value.

// Asynchronous programming using Async and await
<Access Modifier> static async Task Main() { }
<Access Modifier> static async Task<int> Main() { }
<Access Modifier> static async Task Main(string[] args) { }
<Access Modifier> static async Task<int> Main(string[] args) { }

 

string[] args

This is used to supply command-line arguments, where string[] is an array of String datatype with array name ’args’. For example, as shown in the following example we can also iterate elements of string array ’args’ the command line arguments and use them as we like in the Main() method.

But, command-line arguments are optional that means you can remove string[] args part and your Main() method will no longer accept command-line arguments as demonstrated in the following example:


Console.WriteLine(“Hello World!”);

Console is a class in System namespace, that has a method called WriteLine() that can write a string value like “Hello World!” supplied to the standard output. This statement causes the message “Hello, World!” to be displayed on the screen.


; (Semicolon)

Semicolons are statement terminators, which mean any expression, assignment, or declaration statements are supposed to terminate with a semicolon, that represents line termination character.


{ }

Curly braces represent the start and end of the code block, like the start or end of a class or method body.


References


 

Optical Character Recognition

Author of “PowerShell Guide to Python“, “Windows Subsystem for Linux (WSL)” and currently writing the most awaited book: “PowerShell to C# and Back” !


Subscribe to our mailing list

* indicates required