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 textThese 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 variableThese are valid:
age = 26; // OK: assigning a new integer
str = "Jane"; // OK: assigning a new text stringChallenge
BeginnerDeclare the following variables with their corresponding types and values:
- An
intvariable namedcountwith the value10. - A
doublevariable namedtotalwith the value150.75. - A
charvariable namedgradewith the value'A'. - A
boolvariable namedisActivewith the valuefalse. - A
stringvariable nameduserNamewith 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 valuesType 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 variableValid reassignments with same type:
age = 26; // OK: assigning a new integer
str = "Jane"; // OK: assigning a new text stringTry 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);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3