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

Implicit typing with var keyword in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the var keyword do in C#?
The var keyword lets the compiler automatically figure out the variable's type based on the value you assign to it. This is called implicit typing.
Click to reveal answer
beginner
Can you use var without assigning a value right away?
No. When you use var, you must assign a value immediately so the compiler can determine the type.
Click to reveal answer
beginner
What type will this variable have? <br>
var number = 10;
The variable number will be of type int because 10 is an integer.
Click to reveal answer
intermediate
Is var the same as object type?
No. var is not a type itself. It tells the compiler to use the actual type of the assigned value. object is a specific type that can hold any data but is less specific.
Click to reveal answer
intermediate
Why might you want to use var instead of explicitly writing the type?
Using var can make code cleaner and easier to read, especially when the type is obvious or very long to write. It also helps when the exact type is complex or anonymous.
Click to reveal answer
What happens if you write var x; without assigning a value?
Ax is null by default
Bx becomes an object type
CCompiler error because type cannot be inferred
Dx is dynamic type
What type does var name = "hello"; create?
Astring
Bobject
Cvar
Dchar[]
Which of these is a benefit of using var?
AIt makes code shorter and easier to read
BIt disables type checking
CIt makes variables dynamic
DIt allows variables to change type later
Is this code valid? <br>var list = new List<int>();
AYes, but list will be of type object
BYes, the compiler infers the type List<int>
CNo, you must specify the type explicitly
DNo, var cannot be used with generic types
Which statement about var is false?
A<code>var</code> can only be used for local variables
B<code>var</code> requires immediate assignment
C<code>var</code> is resolved at compile time
D<code>var</code> variables can change type after assignment
Explain how the var keyword works in C# and when you should use it.
Think about how the compiler figures out the type and why it helps.
You got /4 concepts.
    Describe the differences between var and object types in C#.
    Consider how the compiler treats each and what happens at runtime.
    You got /4 concepts.