Lessons in this course (38)
2. First program, namespaces and keywords
Classic program structure (what every C# file looked like before C# 9, and what top-level statements generate for you):
using System; // import a namespace so you can write Console instead of System.Console
namespace Divakar.Shop // logical grouping of types; usually matches the folder
{
internal class Program // every method lives inside a type
{
static void Main(string[] args) // entry point: static, named Main, returns void or int (or Task/Task<int>)
{
Console.WriteLine("Hello, Divakar!");
Console.Write("Your name: ");
string? name = Console.ReadLine();
Console.WriteLine($"Welcome {name}"); // string interpolation
}
}
}Modern equivalent (C# 10+):
// GlobalUsings.cs — applies to every file in the project
global using System.Text.Json;
// Customer.cs — file-scoped namespace saves one level of indentation
namespace Divakar.Shop.Models;
public class Customer { public string Name { get; set; } = ""; }
// Program.cs — top-level statements: the compiler creates Program and Main
using Divakar.Shop.Models;
var c = new Customer { Name = "Asha" };
Console.WriteLine(JsonSerializer.Serialize(c));Namespaces:
- Prevent name clashes (
Divakar.Shop.Models.OrdervsDivakar.Billing.Order). usingimports a namespace;using Alias = Some.Long.Namespace.Type;creates an alias;using static System.Math;lets you writeSqrt(2).- Implicit usings (
<ImplicitUsings>enable</ImplicitUsings>in the .csproj) auto-importSystem,System.Linq,System.Collections.Generic,System.IO,System.Threading.Tasksand more. - A namespace is not an assembly: one assembly (DLL) can contain many namespaces and one namespace can span many assemblies.
Keywords are reserved words with special meaning: class, int, if, return, public, static, new, this, base, null, true... You can't use them as identifiers unless prefixed with @ (int @class = 5;). Contextual keywords are only special in certain places and can otherwise be used as names: var, async, await, get, set, init, value, yield, record, required, where, select, field (C# 14).
Naming conventions: PascalCase for types, methods, properties and namespaces; camelCase for locals and parameters; _camelCase for private fields; interfaces start with I (IRepository); async methods end with Async.