Menu
Coddy logo textTech

Type Declaration

Part of the Fundamentals section of Coddy's C# journey — lesson 9 of 69.

Once a variable is declared with a certain type, it can only hold values of that type. For instance, an int variable can only hold integer values, and a string variable can only hold text.

For example:

int age = 25;        // Can only hold whole numbers
string str = "abc";  // Can only hold text

These would cause errors:

age = "defg";  // Error: can't put text in an int variable
str = 25;      // Error: can't put a number in a string variable

These are valid:

age = 26;      // OK: assigning a new integer
str = "Jane";  // OK: assigning a new text string
challenge icon

Challenge

Beginner

Declare the following variables with their corresponding types and values:

  • An int variable named count with the value 10.
  • A double variable named total with the value 150.75.
  • A char variable named grade with the value 'A'.
  • A bool variable named isActive with the value false.
  • A string variable named userName with the value "Bob123".

Cheat sheet

In C#, variables are strongly typed - once declared with a specific type, they can only hold values of that type.

Variable declaration examples:

int age = 25;        // Can only hold whole numbers
string str = "abc";  // Can only hold text
double total = 150.75;  // Can hold decimal numbers
char grade = 'A';    // Can hold single characters
bool isActive = false;  // Can hold true/false values

Type mismatches cause errors:

age = "defg";  // Error: can't put text in an int variable
str = 25;      // Error: can't put a number in a string variable

Valid reassignments with same type:

age = 26;      // OK: assigning a new integer
str = "Jane";  // OK: assigning a new text string

Try it yourself

using System;

public class Program {
    public static void Main(string[] args) {
        // Declare variables here
        
        
        // Output the values
        Console.WriteLine("Count: " + count);
        Console.WriteLine("Total: " + total);
        Console.WriteLine("Grade: " + grade);
        Console.WriteLine("Active: " + isActive);
        Console.WriteLine("User Name: " + userName);
        
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals