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

Null-conditional operator in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the null-conditional operator in C#?
The null-conditional operator is ?. in C#. It allows safe access to members or elements of an object that might be null, preventing exceptions by returning null instead.
Click to reveal answer
beginner
How does ?. help prevent exceptions?
When you use ?., if the object before it is null, the whole expression returns null instead of throwing a NullReferenceException. This makes your code safer and cleaner.
Click to reveal answer
beginner
Example: What does person?.Name do if person is null?
If person is null, person?.Name returns null instead of throwing an error. If person is not null, it returns the Name property.
Click to reveal answer
intermediate
Can the null-conditional operator be used with methods? Give an example.
Yes, you can call a method safely using ?.. For example, person?.GetAge() calls GetAge() only if person is not null. Otherwise, it returns null.
Click to reveal answer
intermediate
What happens when you use the null-conditional operator with an event, like MyEvent?.Invoke()?
Using ?. with events safely invokes the event only if it has subscribers (is not null). This prevents exceptions when no handlers are attached.
Click to reveal answer
What does the null-conditional operator ?. do in C#?
ASafely accesses members of an object that might be null
BThrows an exception if the object is null
CAssigns null to an object
DChecks if an object is not null
What will person?.Name return if person is null?
ADefault value of Name's type
BEmpty string
CThrows NullReferenceException
Dnull
Which of these is a valid use of the null-conditional operator?
Aperson?.GetAge()
Bperson.GetAge()?
Cperson?GetAge()
Dperson.GetAge?.()
How does MyEvent?.Invoke() help when raising events?
AIt always invokes the event
BIt unsubscribes all handlers
CIt invokes the event only if there are subscribers
DIt throws an exception if no subscribers
What type of value does the null-conditional operator return when the object is null?
ADefault value of the member
Bnull
CEmpty string
DZero
Explain how the null-conditional operator ?. works and why it is useful in C#.
Think about how it helps avoid errors when objects might be missing.
You got /4 concepts.
    Describe a scenario where using ?. with an event is beneficial.
    Consider what happens if you try to raise an event with no listeners.
    You got /3 concepts.