Creating a "Hello, World!" Program in C#: Your First Steps in C# Programming
Learn the fundamentals of C# programming by creating a simple "Hello, World!" program. This tutorial provides various code examples, demonstrating basic syntax, namespace usage, and different ways to structure a basic C# program.
Creating a "Hello, World!" Program in C#
Simple C# "Hello, World!" Example
Here's a basic "Hello, World!" program in C#. It demonstrates fundamental C# syntax, including class definitions, methods, and namespace usage.
C# Code
using System;
class Program {
static void Main(string[] args) {
Console.WriteLine("Hello, World!");
}
}
This code defines a class named `Program` containing a `Main` method. The `Main` method calls `Console.WriteLine()` to print "Hello, World!" to the console.
Explanation of the Code
using System;
: Imports the `System` namespace, providing access to core classes (like `Console`).class Program
: Defines a class named `Program`. Classes are blueprints for creating objects.static void Main(string[] args)
: The `Main` method is the entry point of the program (where execution begins).static
: The method belongs to the class itself, not a specific instance of the class.void
: The method doesn't return a value.string[] args
: An array of strings containing command-line arguments (if any).
Console.WriteLine("Hello, World!");
: Prints "Hello, World!" to the console.
Variations on the "Hello, World!" Program
Here are other ways to write the same program, illustrating different aspects of C# syntax:
Using `using System;`
Importing the `System` namespace makes it unnecessary to use `System.Console`.
C# Code
using System;
class Program {
static void Main(string[] args) {
Console.WriteLine("Hello, World!");
}
}
Using `public` Modifier
Adding the `public` modifier makes the class and `Main` method accessible from other code.
C# Code
using System;
public class Program {
public static void Main(string[] args) {
Console.WriteLine("Hello, World!");
}
}
Using a Namespace
Namespaces help organize code into logical groups.
C# Code
using System;
namespace MyNamespace {
public class Program {
public static void Main(string[] args) {
Console.WriteLine("Hello, World!");
}
}
}