MSDN Documentation

.NET Tutorials

Building Your Second .NET App

Congratulations on building your first .NET application! In this tutorial, we'll expand on your knowledge and build a slightly more complex application. We'll focus on common patterns and practices to help you write more robust and maintainable code.

Step 1: Project Setup

Let's create a new console application project. Open your terminal or command prompt and navigate to your desired project directory. Then, run the following command:

dotnet new console -n MySecondApp
cd MySecondApp

This command creates a new console application project named MySecondApp and navigates you into its directory.

Step 2: Understanding the Project Structure

Inside your MySecondApp directory, you'll find a few key files:

  • MySecondApp.csproj: The project file that defines your project's properties, dependencies, and build settings.
  • Program.cs: The main entry point for your application.

Open Program.cs in your favorite code editor. You should see a simple "Hello, World!" program similar to this:

// Program.cs
namespace MySecondApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Step 3: Adding Functionality - User Input

Let's modify the program to ask the user for their name and then greet them personally.

Replace the contents of Program.cs with the following code:

// Program.cs
using System;

namespace MySecondApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to My Second .NET App!");
            Console.Write("Please enter your name: ");
            string? userName = Console.ReadLine(); // The '?' makes userName nullable

            if (!string.IsNullOrEmpty(userName))
            {
                Console.WriteLine($"Hello, {userName}! Nice to meet you.");
            }
            else
            {
                Console.WriteLine("Hello there! It's nice to meet you.");
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
}

Explanation:

  • using System;: Imports the System namespace, which contains essential classes like Console.
  • Console.Write(): Displays text without adding a newline at the end.
  • Console.ReadLine(): Reads a line of text from the console input and returns it as a string. We've used a nullable string (`string?`) to indicate that it might be null.
  • !string.IsNullOrEmpty(userName): A common check to ensure the user actually entered something.
  • String interpolation ($"{variable}"): A convenient way to embed variable values directly into strings.
  • Console.ReadKey(): Waits for the user to press any key before the application exits.

Step 4: Running Your Application

Save the changes to Program.cs. Now, from your terminal within the MySecondApp directory, run the application using the following command:

dotnet run

You should see the welcome message, followed by a prompt for your name. Enter your name and press Enter to see the personalized greeting.

Step 5: Organizing Code with Methods

As your applications grow, it's good practice to break down functionality into smaller, reusable methods. Let's refactor our code to use a separate method for greeting.

Modify Program.cs as follows:

// Program.cs
using System;

namespace MySecondApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to My Second .NET App!");
            string? userName = GetUserName();
            GreetUser(userName);

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }

        static string? GetUserName()
        {
            Console.Write("Please enter your name: ");
            return Console.ReadLine();
        }

        static void GreetUser(string? name)
        {
            if (!string.IsNullOrEmpty(name))
            {
                Console.WriteLine($"Hello, {name}! Nice to meet you.");
            }
            else
            {
                Console.WriteLine("Hello there! It's nice to meet you.");
            }
        }
    }
}

Explanation:

  • We've created two new static methods: GetUserName() and GreetUser().
  • GetUserName() is responsible for prompting the user and returning their input.
  • GreetUser() takes the name as an argument and handles the greeting logic.
  • The Main method now orchestrates these calls, making it cleaner and easier to understand.

Run dotnet run again to test the refactored code. The output should be the same.

Key Takeaways

  • Creating new projects with dotnet new.
  • Basic console input/output using Console.WriteLine, Console.Write, and Console.ReadLine.
  • Handling nullable strings and checking for empty input.
  • String interpolation for formatted output.
  • Breaking down code into smaller, reusable methods.

You've successfully built a second .NET application, incorporating user interaction and basic code organization. Continue exploring the .NET ecosystem to discover more powerful features and build even more sophisticated applications!