Types

View saved

Declare typed variables

C# is statically typed. Name the type or use var with an initializer.

int lessons = 18;
double rating = 4.5;
bool published = true;
char grade = 'A';
Console.WriteLine($"{lessons} {rating} {published} {grade}");

Use var carefully

var still has a fixed type—it is inferred once at compile time.

var title = "C# basics";
// title = 3; // error

Constants

const values must be known at compile time.

const int Max = 20;
Console.WriteLine(Max);

Type habits

  • Prefer clear names over abbreviations
  • Use int for whole numbers and double for most decimals
  • decimal is better for money
  • Convert explicitly with casts or Convert helpers

Comments

One comment per signed-in account. Comments are saved with this page’s URL.