What is the purpose of a question mark after a value type (for example: int? myVariable)?
It means that the value type in question is a nullable type
Nullable types are instances of the System.Nullable struct. A
nullable type can represent the correct range of values for its
underlying value type, plus an additional null value. For example, a
Nullable<Int32>
, pronounced "Nullable of Int32," can be assigned any
value from -2147483648 to 2147483647, or it can be assigned the null
value. ANullable<bool>
can be assigned the values true, false, or
null. The ability to assign null to numeric and Boolean types is
especially useful when you are dealing with databases and other data
types that contain elements that may not be assigned a value. For
example, a Boolean field in a database can store the values true or
false, or it may be undefined.class NullableExample
{
static void Main()
{
int? num = null;
// Is the HasValue property true?
if (num.HasValue)
{
System.Console.WriteLine("num = " + num.Value);
}
else
{
System.Console.WriteLine("num = Null");
}
// y is set to zero
int y = num.GetValueOrDefault();
// num.Value throws an InvalidOperationException if num.HasValue is false
try
{
y = num.Value;
}
catch (System.InvalidOperationException e)
{
System.Console.WriteLine(e.Message);
}
}
}
What does a question mark after a reference type mean in C#?
In C# 8.0, nullable reference types were introduced - this allows you to mark reference types as nullable by appending ?
to the type name.
In null-state analysis, the code is statically checked to keep track of the null-state of references. This analysis can result in one of the 2 states below:
not-null - variable has a non-null value
maybe-null - variable can be null or not-null; the analyser can't determine for sure
This is useful as it helps the compiler provide warnings to help you write code less prone to NullReferenceExceptions
and more consumable by other APIs.
For example, the compiler will emit a warning for the below.
#nullable enable
...
string message = null;
// Warning - CS8602 Dereference of a possibly null reference
Console.WriteLine(message.Length);
This is because since message
was set to null, its state was tracked as maybe-null. This throws a warning to alert you just in case you're trying to access the properties of a null object. And yes, you are.
Here's a different example:
#nullable enable
...
string message = "The quick brown fox jumps over the lazy dog";
// No warning
Console.WriteLine(message.Length);
Since message
is known to not be null, its state is set to not-null. The compiler won't produce a warning as it knows that you can dereference the variable safely. It is definitely not null.
Alternatively, you can also just decide to tell the world that some variables can be null :)
Question mark '?' given in arguments of a method
Simple, this isn’t C++ code. It’s C#, where ?
denotes a nullable value type. I.e. a value type that can also be null
. int?
is a shortcut for Nullable<int>
.
What does one question mark following a variable declaration mean?
This is a nullable type. Nullable types allow value types (e.g. int
s and structures like DateTime) to contain null.
The ?
is syntactic sugar for Nullable<DateTime>
since it's used so often.
To call ToString()
:
if (timstamp.HasValue) { // i.e. is not null
return timestamp.Value.ToString();
}
else {
return "<unknown>"; // Or do whatever else that makes sense in your context
}
Question Mark (?) after session variable reference - What does that mean
It performs a null-check on Session("LightBoxID")
before attempting to call .ToString()
on it.
MS Docs: Null-conditional operators ?.
and ?[]
What does class? (class with question mark) mean in a C# generic type constraint?
It enforces that T has to be a nullable reference type.
The type you set in for T, must derive from object?
.
It's a new feature in C#8, to explictly declare a type as nullable.
if you have
Add<T>(T tmp);
You document, it's OK to Add null;
Check null/empty at multiple levels using question mark operator c#
Use the following:
return dummy?.list?.FirstOrDefault()?.A;
You should avoid using index on a List as Lists aren't deterministic. If you have to know the position of an item in an a collection, use an array.
Related Topics
Why Do I Get "'Property Cannot Be Assigned" When Sending an Smtp Email
Creating Wizards For Windows Forms in C#
Deserializing Json to .Net Object Using Newtonsoft (Or Linq to Json Maybe)
How to Handle Wndproc Messages in Wpf
How to Update the Current Line in a C# Windows Console App
Best Timer For Using in a Windows Service
What Is the { Get; Set; } Syntax in C#
Jquery Ui Dialog With ASP.NET Button Postback
.Net Httpclient. How to Post String Value
Why Use the 'Ref' Keyword When Passing an Object
How to Cast Object of Type 'System.Dbnull' to Type 'System.String'
Awaiting Multiple Tasks With Different Results
Raw SQL Query Without Dbset - Entity Framework Core
Login Failed For User 'Iis Apppool\Asp.Net V4.0'
Calculate the Execution Time of a Method
How to Read Appsettings Values from a .Json File in ASP.NET Core