0
0
C Sharp (C#)programming~20 mins

Variable declaration and initialization in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Variable Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of variable initialization with implicit typing
What is the output of this C# code snippet?
C Sharp (C#)
var number = 10;
var text = "Hello";
var result = number + text.Length;
Console.WriteLine(result);
A15
BHello10
C10
DCompilation error
Attempts:
2 left
💡 Hint
Remember that var infers the type and text.Length returns an integer.
Predict Output
intermediate
2:00remaining
Value of uninitialized variable
What happens when you try to use an uninitialized local variable in C#?
C Sharp (C#)
int x;
// Console.WriteLine(x); // Uncommenting this line causes what?
ACompilation error: Use of unassigned local variable 'x'
BOutputs 0
COutputs garbage value
DRuntime exception
Attempts:
2 left
💡 Hint
Local variables must be assigned before use in C#.
Predict Output
advanced
2:00remaining
Output of variable shadowing in nested scopes
What is the output of this C# code?
C Sharp (C#)
int value = 5;
{
    int value = 10;
    Console.WriteLine(value);
}
Console.WriteLine(value);
A10\n10
B5\n10
C10\n5
DCompilation error due to duplicate variable declaration
Attempts:
2 left
💡 Hint
Check if C# allows redeclaring a variable with the same name in an inner block.
Predict Output
advanced
2:00remaining
Output of nullable variable initialization and usage
What is the output of this C# code?
C Sharp (C#)
int? number = null;
number ??= 100;
Console.WriteLine(number);
Anull
B0
C100
DCompilation error
Attempts:
2 left
💡 Hint
The ??= operator assigns the value only if the variable is null.
🧠 Conceptual
expert
2:00remaining
Behavior of const and readonly variables
Which statement about const and readonly variables in C# is correct?
Aconst variables can be assigned in constructors; readonly variables cannot.
Bconst variables can be assigned only at declaration and are compile-time constants; readonly variables can be assigned at declaration or in constructor and are runtime constants.
CBoth const and readonly variables can be assigned multiple times during runtime.
Dreadonly variables can be assigned only at declaration and are compile-time constants; const variables can be assigned anywhere and are runtime constants.
Attempts:
2 left
💡 Hint
Think about when the values are fixed and where assignments are allowed.