Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
C# and .NET Basics  ›  Lesson

C# — The Language You Write

C# 14 minC# is a statically typed, object-oriented language where every value has a type the compiler checks before the program runs.

C# — The Language You Write

Throughout this course you will build ReadingRoom, a small lending-library API with books, members and loans. Every line of it is C#. Before any web code, you need to read C# comfortably: what a type is, what a class is, and why the compiler rejects code before you ever run it.

The rule

Every value has a type, and the compiler checks it before anything runs.

C# is statically typed. When you declare a variable, its type is fixed. If you try to put the wrong kind of value in it, the build fails — you find the mistake at your desk, not in production.

int copies = 3;              // a whole number
string title = "Dune";       // text
decimal lateFee = 0.50m;     // money: use decimal, not double
bool isOverdue = false;

var year = 1965;             // still an int: var infers, it does not loosen

Types you build yourself are classes and records. A record is a short way to write a type that mostly carries data:

public record Book(int Id, string Title, string Author, int Year);

var book = new Book(1, "Dune", "Frank Herbert", 1965);
Console.WriteLine(book.Title);   // Dune

Modern projects switch on nullable reference types. Then string means "never null" and string? means "might be null", and the compiler warns when you forget to check.

The shortcut

When you read an unfamiliar line of C#, find the type on the left first. It tells you what the value can hold and what you can do with it. var is not a type of its own; read the right-hand side to find the real one.

Reading a line of ReadingRoom codeStep 1 of 4
  1. Find the declared type

    In List<Book> shelf = new(); the type is List<Book>: a growable list that only accepts Book values.

The trap: thinking var makes C# dynamic like JavaScript. It does not. var x = 5; x = "five"; fails, because x became an int on the first line.

Drills

Answer fast — trust the rule.

quick drill

What is the type of total in var total = 12;?

quick drill

When does C# report that int copies = "three"; is wrong?

quick drill

Which type fits a library's late fee of 0.50 best?

quick drill

With nullable reference types on, what does string? Subtitle tell you?

Remember

  • Every value has a type, and the compiler checks it before anything runs.
  • Read the type on the left first; resolve var from the right-hand side.
  • var is still static typing, and ? means "may be null — check it".

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWhy did the build fail?

A teammate writes int copies = "three"; in ReadingRoom and the build fails before anything runs. Explain why, what var would have changed, and how a string? differs from a string.