If you’ve already read the introduction in the previous lesson, take a look here. You’ve become quite familiar with what the C# programming language is, its origins, the changes it has undergone, and you probably have a rough understanding of what the .NET Framework is. If you’ve prepared for learning, made important decisions about which operating system to use, and selected an IDE - Integrated Development Environment to start with, congratulations!
Also, if you’ve successfully installed .NET version 8 (since older versions won’t allow you to code in C# 12), and executed the “Hello, World!” program with a single line of code, then welcome to our second lesson in the C# tutorial. We’ll guide you step by step, in a practical manner, through C# 12 programming.
In this step-by-step tutorial, we’ll explore the fundamentals of C# 12 programming and provide you with everything you need to start coding your first programs effortlessly. Whether it’s a basic calculator app or a sophisticated software system, practicing project development will enhance your skills and provide valuable experience. Remember that programming is an ongoing process of learning and refinement. Stay abreast of trends, explore new technologies, and learn from your mistakes. Always remain open to new knowledge and be adaptable to change.
My First C# Program: A Journey into Coding
Launch your IDE, we utilize VSCode - Visual Studio Code on the Windows 11 operating system. Open the lesson 1 folder, located within the csharp_tutorial directory. If you already have it created on your machine, you've likely completed the first lesson. Then, within the VSCode Terminal panel, enter the following command.
D:\tutorials\csharp12_tutorial\lesson1>
dotnet new console -o MyFirstProgram
In the Explorer panel, examine what the previous command has generated. Click on the Program.rs file and pay attention to the following lines of code:
// See
https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
Run the following commands:
D:\tutorials\csharp12_tutorial\lesson1> cd MyFirstProgram
D:\tutorials\csharp12_tutorial\lesson1\MyFirstProgram>
dotnet run
When the program executes, it will be displayed in the Terminal panel:
D:\tutorials\csharp12_tutorial\lesson1\MyFirstProgram>
Hello, World!
Change the text “Hello, World!”:
Console.WriteLine("Hello, this is my first program in C# 12 programming language.\n");
Restart the program and observe the outcome:
D:\tutorials\csharp12_tutorial\lesson1\MyFirstProgram>
dotnet run
Hello, this is my first
program in C# 12 programming language.
The Console class is part of the .NET Framework
and provides methods for interacting with the standard input, output, and error
streams. It serves as the bridge between your C# program and the operating
system’s console (command-line interface). You can use Console to
read input from the user, display output, and handle errors. And
WriteLine is a method provided by the Console class. In the
given code snippet, we used it to display the text in the console panel
and move the cursor to the next
line.
But what is \n ? This is a string special character sequence and represents the newline character. String Escape Sequences in C# and in many other programming languages are used to represent certain control characters or special characters within strings. They allow precise definition of special characters without conflicting with the language syntax. You can use each of them in the C# programming language, while you will encounter them in many projects because they shorten code writing.
Position your cursor at the top of the Program.cs file and type the following comment in a way you won't often see in tutorials, but you will encounter in projects. Then, add the following documentation comment in the same manner, including your program's name, your full name, the date when you wrote the code, and optionally, a web address where other developers viewing your code can find additional information.
/// <summary>
/// MY FIRST PROGRAM IN C#
12
///
MANUEL RADOVANOVIC, 2024-03-19
///
www.manuelradovanovic.com
///
</summary>
How to Avoid Using Console Throughout the Entire Project?
<Project Sdk="Microsoft.NET.Sdk">
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<!--
This will
automatically include static members of System.Console in every
C# file
within the project, which can be useful if you want this rule to apply
globally to
the entire project.
-->
<ItemGroup>
<Using Include="System.Console" Static="true" />
</ItemGroup>
</Project>
Pay attention, what do we have here? Here we have a part of the project file, .csproj, for the C# project you are currently working on. In it, you can configure certain attributes of your project that will affect the entire project and all files within it.
The first attribute <Project Sdk="Microsoft.NET.Sdk"> defines the SDK - Software Development Kit used for compilation and building the project. In this case, it uses Microsoft.NET.Sdk, which is the base SDK for .NET projects. This means that MSBuild targets and tasks defined in that SDK will be used for compiling and building your code.
In the second attribute <PropertyGroup>, various project properties are defined. For example, OutputType specifies the type of the output file. In this case, it’s an executable file, while TargetFramework defines the target .NET framework (in this case, .NET 8.0). Additionally, you can see ImplicitUsings, which enables implicit using directives for specific namespaces, and Nullable, allowing the use of nullable types in the code.
What we added with these attributes is primarily a comment that explains the rule for including static members of System.Console in every C# file. It can be useful if you want this rule to apply globally to the entire project. That’s why we included it. Go back to Program.cs and modify the following line of code to completely ignore Console throughout the entire project.
WriteLine("Hello, this is my
first program in C# 12 programming language.\n");
How to Avoid Using Console Throughout Only the File We’re Working On?
You can do this even more simply. There’s a higher chance that you’ll use “Avoid Using Console Throughout Only the File” rather than applying it to the entire project. Most of your classes probably won’t use any output to the terminal panel. You’ll likely handle output in fewer files regardless of the project’s size. In any case, you have the choice, and your experience will guide you in finding the right balance or making decisions. Go back to the MyFirstProject.csproj file and comment out the following code.
<ItemGroup>
<Using Include="System.Console" Static="true" />
Then go back to Program.cs and modify it to look like this:
/// <summary>
/// MY FIRST PROGRAM IN C#
///
MANUEL RADOVANOVIC, 2024-03-19
/// www.manuelradovanovic.com
///
</summary>
using static System.Console; /* This will include the System.Console static members
only in the file where the directive is specified */
// This is the code of all your program in a single-line code
WriteLine("Hello, this is my
first program in C# 12 programming language.\n");
// Let's add some text to understand "top-level statements
Write(@"In C# 12, it is
possible to write code consisting of only one line
and one comment using so-called 'top-level statements'. This is
a feature that enables writing smaller programs and scripts without
the need to define a class or Main method. This is not intended for
production.");
Run your program and check the result:
D:\tutorials\csharp12_tutorial\lesson1\MyFirstProgram> dotnet run
Hello, this is my
first program in C# 12 programming language.
In C# 12, it is possible to write code consisting of only one line
and one comment using so-called
'top-level statements'. This is
a feature that enables writing smaller
programs and scripts without
the need to define a class or Main
method. This is not intended for
production.
As you can see in this code, to avoid writing Console only at the file level you’re working on, simply add the following code.
using static System.Console;
Pay attention that in addition to the WriteLine() method, which is used for printing text in a single line on the Terminal panel followed by a new line, you can also use the Write() method. It is used for printing text across multiple lines when you have more text.
#region Directive in C#: Organizing Code with Regions
The #region directive in C# allows you to group related code sections together, making your code more organized and easier to navigate. It’s a helpful tool for collapsing and expanding code blocks within your IDE. Let’s explore how to use it! In C#, you can create a #region by following this syntax:
#region My Region Name
// Your code
here
#endregion
Create two regions in our Program.cs file so that the entire code looks like this:
/// <summary>
/// MY FIRST PROGRAM IN C#
///
MANUEL RADOVANOVIC, 2024-03-19
///
www.manuelradovanovic.com
///
</summary>
using static System.Console; /* This will include the System.Console static members
only in the file where the directive is specified */
/* The region is a
preprocessor directive that allows grouping parts of code
for better
organization and readability. */
#region Learn Comments in C#
program language
#region My first C# program
Run the program, and you’ll see that organizing your code into regions won’t affect the program’s execution. Just keep in mind that having too many #region blocks is not recommended in practice.
The Role of Comments in Sustainable C# Application Development
In the world of software development, writing clean, maintainable code is essential. One often overlooked aspect of code quality is the proper use of comments. Comments serve as a bridge between the developer’s intent and the actual code, providing valuable context and aiding in understanding. By following best practices and using comments judiciously, developers contribute to a more robust and comprehensible codebase.
Remember, comments are not a substitute for self-explanatory code. Strive for a balance between clear comments and clean, expressive code. Add the following code to Program.cs!
/* The region is a preprocessor directive that allows grouping parts of code
for better
organization and readability. */
#region Learn Comments in C#
program language
/// <summary>
/// These comments
used to generate documentation from your code.
/// </summary>
/*
This is a multi-line
comment.
It can span multiple lines.
*/
// This is a single-line comment
#endregion
Top-level statements in C# 12 allow you to write executable code directly at the root of a file without needing a class or namespace declaration. Instead of wrapping your code in a class and a Main method, you can create programs without the ceremony of a Program class. Top-level statements minimize boilerplate code, making it easier to get started with small utilities, such as Azure Functions or GitHub Actions.
When you write your code directly at the top level of a file, the compiler generates a Program class with an entry point method (not named Main) for your application. The generated method is an implementation detail that your code can’t reference directly. Top-level statements simplify small programs and provide a smooth path from experimentation to full applications.
If you want to use the Main() entry method, then when creating a new project, use the following command:
D:\tutorials\csharp12_tutorial\lesson1>
dotnet new console –use-program-main -o MainMethod
Click on Program.cs in the newly created MainMethod structure. Add some comments and execute the program.
// METHOD MAIN
// MANUEL RADOVANOVIC,
2024-03-20
//
www.manuelradovanovic.com
// Include the System.Console static members
// only in the file where
the directive is specified
using static System.Console;
// Define the namespace for the code.
namespace methodmain;
// Define a class named Program.
class Program
{
// Define the
entry point method for the program.
static void Main(string[] args)
{
// Output "Hello, World!" to the console.
WriteLine("Hello, World!");
}
}
You can see how the entire program was created and coded in the following video, too.
No comments:
Post a Comment