.NET

C# Language Essentials

Nullable types, generics, attributes, extension methods, type casting, advanced enums

15 interview questions·
Junior
1

What is the correct syntax to declare a nullable int variable in C#?

Answer

In C#, a nullable type for value types is declared with the '?' suffix after the type (int?, bool?, DateTime?). This allows value types to have a null value, which is not possible by default. Nullable types are useful to represent the absence of value in database or API scenarios.

2

Which operator allows providing a default value if a nullable variable is null?

Answer

The null-coalescing operator '??' returns the left-hand value if it is not null, otherwise the right-hand value. This operator is very useful for handling nullable types and avoiding NullReferenceException. There is also the '??=' operator for conditional assignment introduced in C# 8.

3

What is the difference between casting with '(Type)' and 'as' in C#?

Answer

The cast '(Type)object' throws an InvalidCastException if the conversion fails, while the 'as' operator returns null on failure. The 'as' operator only works with reference types and nullable value types. Use 'as' to avoid exceptions in cases where null is an acceptable value.

4

How to check if a nullable variable has a value before using it?

5

What is the syntax to declare a generic class with a type constraint?

+12 interview questions

Master .NET for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free