C# types, variables, operators and arrays
This is the first stop in the C# basics path. It covers the building blocks every later page assumes: how C# stores values in typed variables, how operators combine and compare those values, how arrays hold several values of the same type, and how namespaces and using directives keep a growing program organized. Every sample is part of one small order calculator for an invented online shop, OrdersPortal.
What you’ll build
Section titled “What you’ll build”By the end you will have a console program that prices a three-line order: it multiplies unit prices by quantities, applies a coupon, decides whether shipping is free, works out how many boxes the parcel needs and prints a summary. Along the way you will see why 7 / 2 is 3 in C#, why money uses decimal, why changing one array variable can change another, and how to fix the compiler errors beginners hit most often.
Prerequisites
Section titled “Prerequisites”- The .NET 10 SDK or later. The samples on this page were compiled and run with .NET SDK 10.0.115, which uses C# 14 by default; nothing here needs a version newer than C# 10.
- A terminal and any editor. Visual Studio Code with the C# Dev Kit or Visual Studio 2026 both work.
- A new console project:
dotnet new console -o OrdersPortal.Basicscd OrdersPortal.Basicsdotnet runThe template prints Hello, World!. Replace the contents of Program.cs with each sample below and run dotnet run again. The template enables top-level statements (no Main method needed), nullable reference types and implicit using directives, which the last two sections explain.
Several samples set CultureInfo.CurrentCulture to the invariant culture on their first line. That only makes numbers print with a dot as the decimal separator on every machine, so your output matches the page; remove it and C# formats numbers for your own region.
Variables and data types
Section titled “Variables and data types”A variable is a named storage location with a type. C# is statically typed: the compiler knows the type of every variable and rejects code that puts the wrong kind of value into it, before the program ever runs. You either write the type (int quantity = 3;) or let the compiler infer it from the initializer with var (var productName = "USB-C cable";). An inferred variable is still strictly typed; var only saves typing.
The built-in types you will use most are int (whole numbers), decimal (exact base-10 numbers, the right choice for money), double (fast binary floating point, right for measurements), bool, char (one UTF-16 character) and string. A const is a value fixed at compile time. Adding ? to a reference type such as string? tells the compiler the variable may hold null.
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; // same output on every machine
const decimal VatRate = 0.20m; // compile-time constant
int quantity = 3;decimal unitPrice = 19.99m; // m suffix: decimal literal, the right type for moneyvar productName = "USB-C cable"; // inferred as stringbool isGift = false;char sizeCode = 'M';double weightKg = 0.25;string? giftMessage = null; // ? marks a reference that may be null
decimal net = quantity * unitPrice;decimal gross = Math.Round(net * (1 + VatRate), 2);
Console.WriteLine($"{quantity} x {productName} (size {sizeCode})");Console.WriteLine($"Net: {net}, gross: {gross}");Console.WriteLine($"Gift: {isGift}, message: {giftMessage ?? "(none)"}, weight: {weightKg * quantity} kg");Console.WriteLine($"productName is a {productName.GetType()}");
// Value types are copied; reference types share one objectint reserved = 5;int copy = reserved;copy = 10;Console.WriteLine($"reserved = {reserved}, copy = {copy}");
int[] stock = { 5, 8 };int[] sameStock = stock; // copies the reference, not the arraysameStock[0] = 0;Console.WriteLine($"stock[0] = {stock[0]}");Run it with dotnet run. You should see:
3 x USB-C cable (size M)Net: 59.97, gross: 71.96Gift: False, message: (none), weight: 0.75 kgproductName is a System.Stringreserved = 5, copy = 10stock[0] = 0The last two blocks show the most important idea on this page. int, decimal, double, bool, char and structs are value types: assignment copies the value, so changing copy leaves reserved alone. Classes, strings and arrays are reference types: the variable holds a reference to an object on the heap, so sameStock = stock makes two variables that point at the same array. Strings are reference types that behave like values because they can never be changed in place.
const works for numbers, bool, char and strings known at compile time. When a value is only known at run time but must never change after an object is created, use a readonly field instead; fields belong to classes, which the classes and objects page covers. readonly cannot be applied to a local variable.
Operators
Section titled “Operators”Operators combine and compare values. The arithmetic operators are +, -, *, / and % (remainder). Comparisons (==, !=, <, >, <=, >=) produce a bool, and the logical operators && (and), || (or) and ! (not) combine bool values. && and || short-circuit: the right side is skipped when the left side already decides the answer. The conditional operator condition ? a : b picks one of two values. Two operators deal with null: ?? supplies a fallback when the left side is null, and ?. reads a member only when the object is not null. Compound assignment (+=, *=) and increment (++) update a variable in place.
int itemsOrdered = 7;int boxSize = 2;
Console.WriteLine(itemsOrdered / boxSize); // integer division truncatesConsole.WriteLine(itemsOrdered % boxSize); // remainderConsole.WriteLine((double)itemsOrdered / boxSize); // cast first for a fractional result
int fullBoxes = itemsOrdered / boxSize;int boxesNeeded = fullBoxes + (itemsOrdered % boxSize > 0 ? 1 : 0); // conditional operatorConsole.WriteLine($"Boxes needed: {boxesNeeded}");
decimal orderTotal = 120m;bool isMember = true;bool freeShipping = orderTotal >= 100m || isMember; // comparison + logical ORbool needsReview = orderTotal > 1_000m && !isMember; // logical AND and NOTConsole.WriteLine($"Free shipping: {freeShipping}, needs review: {needsReview}");
string? couponCode = null;Console.WriteLine(couponCode ?? "NO-COUPON"); // null-coalescing: fallback when nullConsole.WriteLine(couponCode?.Length ?? 0); // null-conditional: no exception when null
int loyaltyPoints = 10;loyaltyPoints += 5; // compound assignment: loyaltyPoints = loyaltyPoints + 5loyaltyPoints *= 2;loyaltyPoints++; // incrementConsole.WriteLine($"Points: {loyaltyPoints}");
Console.WriteLine(2 + 3 * 4); // * binds tighter than +Console.WriteLine((2 + 3) * 4); // parentheses make intent explicitOutput:
313.5Boxes needed: 4Free shipping: True, needs review: FalseNO-COUPON0Points: 311420The first line is the classic beginner surprise. When both operands are int, / performs integer division and throws away the fraction, so 7 / 2 is 3. Assigning the result to a double does not help, because the division has already happened; cast one operand first, as (double)itemsOrdered / boxSize does. Dividing an int by zero throws DivideByZeroException, while dividing a double by zero gives infinity. The numeric literal 1_000m uses digit separators, which C# ignores; they only make large numbers readable.
Precedence follows school arithmetic: *, / and % bind tighter than + and -, and comparisons bind tighter than &&, which binds tighter than ||. Add parentheses whenever a reader might hesitate. The null handling hub covers ??, ?. and ??= in depth, and the control flow and operators hub covers checked arithmetic, the unsigned right shift and user-defined compound assignment.
Arrays
Section titled “Arrays”An array stores a fixed number of values of one type. You create it with an initializer ({ "CABLE-01", ... }) or with new int[3], which fills every element with the type’s default value (0 for numbers, false for bool, null for reference types). Indexes start at 0, Length gives the number of elements, and ^1 (C# 8 and later) means “the last element”. Arrays are reference types, as the variables section showed, and their length can never change after creation; when you need a list that grows, use List<T> from the collections and queries hub.
string[] skus = { "CABLE-01", "MOUSE-02", "DOCK-03" };int[] quantities = new int[3]; // three elements, each 0 (the default for int)quantities[0] = 2;quantities[2] = 1;
Console.WriteLine($"Lines: {skus.Length}, first: {skus[0]}, last: {skus[^1]}");
for (int i = 0; i < skus.Length; i++){ Console.WriteLine($"{skus[i]} x {quantities[i]}");}
int totalItems = 0;foreach (int q in quantities){ totalItems += q;}Console.WriteLine($"Total items: {totalItems}");
try{ Console.WriteLine(skus[3]); // valid indexes are 0, 1 and 2}catch (IndexOutOfRangeException ex){ Console.WriteLine($"Error: {ex.Message}");}
// Rectangular (multi-dimensional) array: every row has the same lengthint[,] weeklyOrders = new int[2, 7]; // 2 warehouses x 7 daysweeklyOrders[1, 6] = 42;Console.WriteLine($"Rank: {weeklyOrders.Rank}, cells: {weeklyOrders.Length}, Sunday at warehouse 2: {weeklyOrders[1, 6]}");
// Jagged array: an array of arrays, each row with its own lengthint[][] parcelsPerOrder = new int[2][];parcelsPerOrder[0] = new[] { 1, 2, 3 };parcelsPerOrder[1] = new[] { 4 };Console.WriteLine($"Order 1 has {parcelsPerOrder[0].Length} parcels, order 2 has {parcelsPerOrder[1].Length}");
Array.Sort(skus, StringComparer.Ordinal);Console.WriteLine(string.Join(", ", skus));Output:
Lines: 3, first: CABLE-01, last: DOCK-03CABLE-01 x 2MOUSE-02 x 0DOCK-03 x 1Total items: 3Error: Index was outside the bounds of the array.Rank: 2, cells: 14, Sunday at warehouse 2: 42Order 1 has 3 parcels, order 2 has 1CABLE-01, DOCK-03, MOUSE-02Use for when you need the index (here, to line up two arrays) and foreach when you only need each value. Reading skus[3] does not return null or a default value as some languages do: C# checks every index and throws IndexOutOfRangeException. A rectangular array such as int[,] is one block where every row has the same length; a jagged array int[][] is an array whose elements are separate arrays of any length. Array.Sort sorts in place; passing StringComparer.Ordinal makes string sorting independent of the machine’s culture.
Namespaces
Section titled “Namespaces”A namespace groups related types and gives them a full name, so two types called Invoice can live side by side as OrdersPortal.Billing.Invoice and OrdersPortal.Reporting.Invoice. Namespace names usually follow the folder structure of the project, with the company or product name first. You can always write the fully qualified name; a using directive lets you write the short name instead. When two imported namespaces contain a type with the same name, the short name becomes ambiguous and you either fully qualify it or create an alias.
The sample declares two namespaces with block syntax in the same file as the top-level statements, which must come first. The record keyword is a short way to declare a small data type; the types and records hub explains it.
using OrdersPortal.Billing; // import a namespaceusing ReportInvoice = OrdersPortal.Reporting.Invoice; // alias one type to avoid a clash
System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;var invoice = new Invoice("INV-1001", 59.97m); // OrdersPortal.Billing.Invoicevar summary = new ReportInvoice("INV-1001"); // OrdersPortal.Reporting.Invoicevar archived = new OrdersPortal.Reporting.Archive(); // fully qualified name, no using needed
Console.WriteLine(invoice.GetType().FullName);Console.WriteLine(summary.GetType().FullName);Console.WriteLine(archived.GetType().FullName);Console.WriteLine($"{invoice.Number}: {invoice.Amount}");
namespace OrdersPortal.Billing{ public record Invoice(string Number, decimal Amount);}
namespace OrdersPortal.Reporting{ public record Invoice(string Number); public class Archive { }}Output:
OrdersPortal.Billing.InvoiceOrdersPortal.Reporting.InvoiceOrdersPortal.Reporting.ArchiveINV-1001: 59.97In a real project each type lives in its own file, and most files use a file-scoped namespace (C# 10 and later): namespace OrdersPortal.Shipping; on one line applies to everything in the file and saves a level of indentation. A file can contain only one file-scoped namespace, and it cannot be mixed with block namespaces in the same file.
Using directives
Section titled “Using directives”A using directive at the top of a file imports a namespace for that file. Three variants are worth knowing early:
using static System.Math;imports the static members of one type, so you can writeRound(...)instead ofMath.Round(...).using Json = System.Text.Json.JsonSerializer;creates an alias, useful to resolve a name clash or shorten a long name.global using System.Globalization;(C# 10 and later) imports a namespace into every file in the project. Keep global usings together in one file such asGlobalUsings.cs.
The console template already turns on implicit usings with <ImplicitUsings>enable</ImplicitUsings> in the project file. The SDK then generates global usings for System, System.IO, System.Collections.Generic, System.Linq, System.Net.Http, System.Threading and System.Threading.Tasks, which is why the earlier samples could call Console.WriteLine and use StringComparer without any using line.
This sample has three files. Create GlobalUsings.cs and ShippingLabel.cs next to Program.cs:
global using System.Globalization; // C# 10: imported into every file of the projectnamespace OrdersPortal.Shipping; // file-scoped namespace (C# 10): applies to the whole file
public record ShippingLabel(string OrderId, string City);using static System.Math; // static import: call Round, Max without "Math."using Json = System.Text.Json.JsonSerializer;using OrdersPortal.Shipping;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; // CultureInfo comes from the global using
decimal weight = 2.345m;Console.WriteLine(Round(weight, 1)); // Math.Round through using staticConsole.WriteLine(Max(3, 7));
var label = new ShippingLabel("ORD-42", "Lisbon");Console.WriteLine(Json.Serialize(label)); // System.Text.Json through an alias
// using STATEMENT (not a directive): disposes the writer at the end of the blockusing (var writer = new StringWriter()){ writer.Write($"Label for {label.OrderId}"); Console.WriteLine(writer.ToString());}Output:
2.37{"OrderId":"ORD-42","City":"Lisbon"}Label for ORD-42Do not confuse the using directive with the using statement at the end of the sample. They share a keyword but are unrelated: the directive imports names at compile time, while the statement calls Dispose() on an object when the block ends, even if an exception is thrown. The resource management hub covers the statement and its shorter using var form, and the code organization hub covers global usings and file-scoped namespaces in depth.
Complete working result
Section titled “Complete working result”This program ties the page together: typed variables and constants, arrays walked with a for loop, integer division and remainder for the box count, ?? and the conditional operator, and a namespace holding the pricing rules.
using System.Globalization;using OrdersPortal.Pricing;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
string[] skus = { "CABLE-01", "MOUSE-02", "DOCK-03" };decimal[] unitPrices = { 9.99m, 24.50m, 89.00m };int[] quantities = { 3, 1, 1 };string? couponCode = "WELCOME10";
decimal net = 0m;int itemCount = 0;for (int i = 0; i < skus.Length; i++){ decimal lineTotal = unitPrices[i] * quantities[i]; net += lineTotal; itemCount += quantities[i]; Console.WriteLine($"{skus[i],-9} {quantities[i],2} x {unitPrices[i],6} = {lineTotal,7}");}
decimal discount = couponCode is null ? 0m : Math.Round(net * PriceRules.CouponRate, 2);decimal shipping = net - discount >= PriceRules.FreeShippingFrom ? 0.00m : PriceRules.ShippingFee;decimal total = net - discount + shipping;int boxes = itemCount / PriceRules.ItemsPerBox + (itemCount % PriceRules.ItemsPerBox > 0 ? 1 : 0);
Console.WriteLine($"Items: {itemCount} in {boxes} box(es)");Console.WriteLine($"Net: {net}, discount ({couponCode ?? "none"}): {discount}, shipping: {shipping}");Console.WriteLine($"Total: {total}");
namespace OrdersPortal.Pricing{ public static class PriceRules { public const decimal CouponRate = 0.10m; public const decimal FreeShippingFrom = 100m; public const decimal ShippingFee = 4.95m; public const int ItemsPerBox = 4; }}Output:
CABLE-01 3 x 9.99 = 29.97MOUSE-02 1 x 24.50 = 24.50DOCK-03 1 x 89.00 = 89.00Items: 5 in 2 box(es)Net: 143.47, discount (WELCOME10): 14.35, shipping: 0.00Total: 129.12Try changing couponCode to null, or raising a quantity, and predict the output before you run it. The alignment specifiers such as {skus[i],-9} pad values to a fixed width; the string literals and interpolation hub explains them.
Troubleshooting
Section titled “Troubleshooting”These are the exact compiler messages from the .NET 10 SDK for the mistakes this page warns about.
| Error | Cause | Fix |
|---|---|---|
CS0029: Cannot implicitly convert type 'string' to 'int' |
Assigning a value of the wrong type, often to a var variable that was inferred as int. |
var fixes the type at the declaration. Declare a new variable or convert with int.Parse. |
CS0818: Implicitly-typed variables must be initialized |
var x; with no value. |
Give it an initializer or write the type explicitly. |
CS0664: Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type |
decimal price = 19.99; |
Write 19.99m. |
CS0165: Use of unassigned local variable 'total' |
Reading a local variable before giving it a value. | Initialize it, for example int total = 0;. |
CS0246: The type or namespace name 'Invoice' could not be found (are you missing a using directive or an assembly reference?) |
The type lives in a namespace you have not imported, or the name is misspelled. | Add the using directive or write the fully qualified name. |
CS0104: 'Invoice' is an ambiguous reference between 'OrdersPortal.Billing.Invoice' and 'OrdersPortal.Reporting.Invoice' |
Two imported namespaces contain the same type name. | Fully qualify one, or add a using alias. |
IndexOutOfRangeException at run time |
An index below 0 or at or above Length. |
Loop with i < array.Length, or check the index first. |
Check your understanding
Section titled “Check your understanding”- Is
varin C# dynamic typing, likevarin JavaScript? No. The compiler infers the type once from the initializer, and the variable keeps that type.var count = 5; count = "five";is a compile error. - What does
7 / 2evaluate to when both operands areint, and how do you get3.5? It is3, because integer division truncates. Cast one operand before dividing:(double)7 / 2. - After
int[] b = a; b[0] = 9;, what isa[0]? It is9. Arrays are reference types, soaandbrefer to the same array. For anintvariable the same steps would leave the original unchanged. - What is the difference between
constand areadonlyfield? Aconstvalue must be known at compile time and is baked into every caller. Areadonlyfield is assigned once at run time, in its declaration or a constructor, and cannot change afterwards. - What is the difference between a
usingdirective and ausingstatement? The directive imports a namespace so you can use short type names. The statement disposes an object at the end of a block.
Next steps
Section titled “Next steps”Continue with control flow and methods, which turns these values into decisions, loops and reusable methods, and shows how to handle errors with exceptions.
Related pages
Section titled “Related pages”- C# basics overview: the full reading path.
- Null handling hub:
??,?.,??=and nullable reference types. - Collections and queries hub: lists, dictionaries, collection expressions and LINQ.
- Code organization hub: global usings, file-scoped namespaces and top-level statements.
- Control flow and operators hub: checked arithmetic,
>>>and user-defined compound assignment.