• Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How to set null value to int in c#?

How can I set value to null above?

Any help will be appreciated.

p.s.w.g's user avatar

  • possible duplicate of Why type "int" is never equal to 'null'? –  Sergey Berezovskiy Commented Oct 22, 2013 at 15:36
  • 1 Note that 'value' is a keyword in C#. This code presented is legal C#, but probably a bad idea to use. msdn.microsoft.com/en-us/library/vstudio/a1khb4f8.aspx –  Aric TenEyck Commented Oct 22, 2013 at 15:38
  • @Aric TenEyck Not saying it makes it right, but some framework method parameters have the name value . For example, Enum.Parse , String.IndexOf and (logically) Dictionary<,>.TryGetValue . –  Lance U. Matthews Commented Oct 22, 2013 at 16:04

6 Answers 6

In .Net, you cannot assign a null value to an int or any other struct. Instead, use a Nullable<int> , or int? for short:

Further Reading

  • Nullable Types (C# Programming Guide)
  • I was trying to assign null from immediate window for debugging purpose. It didn't work though. How can this be achieved? –  Mahendran Commented Dec 26, 2018 at 12:10
  • @mahemadhi probably for the same reason you can't do it in regular code. If a variable is declared as an int , it cannot receive null as a value, even while debugging. You need to declare it as an int? . –  p.s.w.g Commented Dec 27, 2018 at 16:19
  • the variable is declared nullable . Yet in immediate window, I couldn't assign null. –  Mahendran Commented Dec 29, 2018 at 4:30
  • cannot assign null value to "int?", getting System.InvalidOperationException –  Kasim Husaini Commented Jun 8, 2023 at 5:41

Additionally, you cannot use "null" as a value in a conditional assignment. e.g...

FAILS with: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'.

So, you have to cast the null as well... This works:

UPDATE (Oct 2021):

As of C# 9.0 you can use " Target-Typed " conditional expresssions, and the example will now work as c# 9 can pre-determine the result type by evaluating the expression at compile-time.

doublehelix's user avatar

  • 7 Excellent. Solved an issue I was having tonight. –  Ron Commented Apr 13, 2016 at 21:02
  • 2 Ok, this is not strictly the answer to the question but I find it really useful. Anyone know the reason of this behaviour? –  Cirelli94 Commented Oct 26, 2017 at 8:29
  • 1 @Cirelli94 The ternary operator ?: tries to deduce the type of the result. It gets int for the first part and null for the second part. It can't implicitly resolve those two. But, when casting the null to be a Nullable<int> (shorthand int? ) then the implicit cast of int to int? is found and used for the final assignment. –  Jesse Chisholm Commented Oct 20, 2021 at 1:20

You cannot set an int to null . Use a nullable int ( int? ) instead:

Jon's user avatar

  • above expression gives "System.InvalidOperationException: Nullable object must have a value." exception. –  Kasim Husaini Commented Jun 8, 2023 at 5:40

int does not allow null, use-

Vadim Martynov's user avatar

The null keyword is a literal that represents a null reference, one that does not refer to any object. In programming, nullable types are a feature of the type system of some programming languages which allow the value to be set to the special value NULL instead of the usual possible values of the data type.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null https://en.wikipedia.org/wiki/Null

Amadeu Antunes's user avatar

Declare you integer variable as nullable eg: int? variable=0; variable=null;

Francis Tchatchoua's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c# .net null int nullable or ask your own question .

  • The Overflow Blog
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Are There U.S. Laws or Presidential Actions That Cannot Be Overturned by Successor Presidents?
  • What is the correct pipeline to process redirection logic
  • How to find the names of strings used in scripting, like the Bounding Box?
  • Is it possible to monitor the current drawn by a computer from an outlet on the computer?
  • Is the forced detention of adult students by private universities legal?
  • What are some limitations of this learning method?
  • Determining Entropy in PHP
  • How does Devarim 28:68 jive with the opinion that positive public prophecies are never reversed?
  • How is AC and DC defined?
  • Sent money to rent an apartment, landlord delaying refund with excuses. Is this a scam?
  • Is it possible to make sand from bones ? Would it have the same properties as regular sand?
  • How to integrate functions with floor function ? Please explain me.
  • Is there a way to hide/show seams on model?
  • Removing undermount sink
  • Calm and Insight is the Normative Meditative Practice in Buddhism
  • Establishing Chirality For a 4D Person?
  • Futuristic/Dystopian teen book trilogy with people that can breathe underwater
  • Big bang and the horizon problem
  • Count squares in my pi approximation
  • My one-liner 'delete old files' command finds the right files but will not delete them
  • Disable Firefox feature to choose its own DNS
  • How to react to a rejection based on a single one-line negative review?
  • "First et al.", many authors with same surname, and IEEE citations
  • meaning of a sentence from Agatha Christie (Murder of Roger Ackroyd)

assignment null c#

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Nullable reference types

  • 23 contributors

In a nullable-oblivious context, all reference types were nullable. Nullable reference types refers to a group of features enabled in a nullable aware context that minimize the likelihood that your code causes the runtime to throw System.NullReferenceException . Nullable reference types includes three features that help you avoid these exceptions, including the ability to explicitly mark a reference type as nullable :

  • Improved static flow analysis that determines if a variable might be null before dereferencing it.
  • Attributes that annotate APIs so that the flow analysis determines null-state .
  • Variable annotations that developers use to explicitly declare the intended null-state for a variable.

The compiler tracks the null-state of every expression in your code at compile time. The null-state has one of three values:

  • not-null : The expression is known to be not- null .
  • maybe-null : The expression might be null .
  • oblivious : The compiler can't determine the null-state of the expression.

Variable annotations determine the nullability of a reference type variable:

  • non-nullable : If you assign a null value or a maybe-null expression to the variable, the compiler issues a warning. Variables that are non-nullable have a default null-state of not-null .
  • nullable : You can assign a null value or a maybe-null expression to the variable. When the variable's null-state is maybe-null , the compiler issues a warning if you dereference the variable. The default null-state for the variable is maybe-null .
  • oblivious : You can assign a null value or a maybe-null expression to the variable. The compiler doesn't issue warnings when you dereference the variable, or when you assign a maybe-null expression to the variable.

The oblivious null-state and oblivious nullability match the behavior before nullable reference types were introduced. Those values are useful during migration, or when your app uses a library that hasn't enabled nullable reference types.

Null-state analysis and variable annotations are disabled by default for existing projects—meaning that all reference types continue to be nullable. Starting in .NET 6, they're enabled by default for new projects. For information about enabling these features by declaring a nullable annotation context , see Nullable contexts .

The rest of this article describes how those three feature areas work to produce warnings when your code might be dereferencing a null value. Dereferencing a variable means to access one of its members using the . (dot) operator, as shown in the following example:

When you dereference a variable whose value is null , the runtime throws a System.NullReferenceException .

Similarly warnings can be produced when [] notation is used to access a member of an object when the object is null :

You'll learn about:

  • The compiler's null-state analysis : how the compiler determines if an expression is not-null, or maybe-null.
  • Attributes that are applied to APIs that provide more context for the compiler's null-state analysis.
  • Nullable variable annotations that provide information about your intent for variables. Annotations are useful for fields to set the default null-state at the beginning of member methods.
  • The rules governing generic type arguments . New constraints were added because type parameters can be reference types or value types. The ? suffix is implemented differently for nullable value types and nullable reference types.
  • Nullable contexts help you migrate large projects. You can enable nullable contexts or warnings in parts of your app as you migrate. After you address more warnings, you can enable nullable reference types for the entire project.

Finally, you learn known pitfalls for null-state analysis in struct types and arrays.

You can also explore these concepts in our Learn module on Nullable safety in C# .

null-state analysis

When nullable reference types are enabled, Null-state analysis tracks the null-state of references. An expression is either not-null or maybe-null . The compiler determines that a variable is not-null in two ways:

  • The variable has been assigned a value that is known to be not-null .
  • The variable has been checked against null and hasn't been modified since that check.

When nullable reference types aren't enabled, all expressions have the null-state of oblivious . The rest of the section describes the behavior when nullable reference types are enabled.

Any variable that the compiler hasn't determined as not-null is considered maybe-null . The analysis provides warnings in situations where you might accidentally dereference a null value. The compiler produces warnings based on the null-state .

  • When a variable is not-null , that variable might be dereferenced safely.
  • When a variable is maybe-null , that variable must be checked to ensure that it isn't null before dereferencing it.

Consider the following example:

In the preceding example, the compiler determines that message is maybe-null when the first message is printed. There's no warning for the second message. The final line of code produces a warning because originalMessage might be null. The following example shows a more practical use for traversing a tree of nodes to the root, processing each node during the traversal:

The previous code doesn't generate any warnings for dereferencing the variable current . Static analysis determines that current is never dereferenced when it's maybe-null . The variable current is checked against null before current.Parent is accessed, and before passing current to the ProcessNode action. The previous examples show how the compiler determines null-state for local variables when initialized, assigned, or compared to null .

The null-state analysis doesn't trace into called methods. As a result, fields initialized in a common helper method called by all constructors generates a warning with the following template:

Non-nullable property ' name ' must contain a non-null value when exiting constructor.

You can address these warnings in one of two ways: Constructor chaining , or nullable attributes on the helper method. The following code shows an example of each. The Person class uses a common constructor called by all other constructors. The Student class has a helper method annotated with the System.Diagnostics.CodeAnalysis.MemberNotNullAttribute attribute:

A number of improvements to definite assignment and null-state analysis were added in C# 10. When you upgrade to C# 10, you may find fewer nullable warnings that are false positives. You can learn more about the improvements in the features specification for definite assignment improvements .

Nullable state analysis and the warnings the compiler generates help you avoid program errors by dereferencing null . The article on resolving nullable warnings provides techniques for correcting the warnings most likely seen in your code.

Attributes on API signatures

The null-state analysis needs hints from developers to understand the semantics of APIs. Some APIs provide null checks, and should change the null-state of a variable from maybe-null to not-null . Other APIs return expressions that are not-null or maybe-null depending on the null-state of the input arguments. For example, consider the following code that displays a message in upper case:

Based on inspection, any developer would consider this code safe, and shouldn't generate warnings. However the compiler doesn't know that IsNull provides a null check and issues a warning for the message.ToUpper() statement, considering message to be a maybe-null variable. Use the NotNullWhen attribute to fix this warning:

This attribute informs the compiler, that, if IsNull returns false , the parameter s isn't null. The compiler changes the null-state of message to not-null inside the if (!IsNull(message)) {...} block. No warnings are issued.

Attributes provide detailed information about the null-state of arguments, return values, and members of the object instance used to invoke a member. The details on each attribute can be found in the language reference article on nullable reference attributes . As of .NET 5, all .NET runtime APIs are annotated. You improve the static analysis by annotating your APIs to provide semantic information about the null-state of arguments and return values.

Nullable variable annotations

The null-state analysis provides robust analysis for local variables. The compiler needs more information from you for member variables. The compiler needs more information to set the null-state of all fields at the opening bracket of a member. Any of the accessible constructors could be used to initialize the object. If a member field might ever be set to null , the compiler must assume its null-state is maybe-null at the start of each method.

You use annotations that can declare whether a variable is a nullable reference type or a non-nullable reference type . These annotations make important statements about the null-state for variables:

  • The variable must be initialized to a non-null value.
  • The variable can never be assigned the value null . The compiler issues a warning when code assigns a maybe-null expression to a variable that shouldn't be null.
  • The variable might only be dereferenced when the compiler can guarantee that the value isn't null .
  • These variables might be initialized with the default null value and might be assigned the value null in other code.
  • The compiler doesn't issue warnings when code assigns a maybe-null expression to a variable that might be null.

Any non-nullable reference variable has a default null-state of not-null . Any nullable reference variable has the initial null-state of maybe-null .

A nullable reference type is noted using the same syntax as nullable value types : a ? is appended to the type of the variable. For example, the following variable declaration represents a nullable string variable, name :

When nullable reference types are enabled, any variable where the ? isn't appended to the type name is a non-nullable reference type . That includes all reference type variables in existing code once you enable this feature. However, any implicitly typed local variables (declared using var ) are nullable reference types . As the preceding sections showed, static analysis determines the null-state of local variables to determine if they're maybe-null before dereferencing it.

Sometimes you must override a warning when you know a variable isn't null, but the compiler determines its null-state is maybe-null . You use the null-forgiving operator ! following a variable name to force the null-state to be not-null . For example, if you know the name variable isn't null but the compiler issues a warning, you can write the following code to override the compiler's analysis:

Nullable reference types and nullable value types provide a similar semantic concept: A variable can represent a value or object, or that variable might be null . However, nullable reference types and nullable value types are implemented differently: nullable value types are implemented using System.Nullable<T> , and nullable reference types are implemented by attributes read by the compiler. For example, string? and string are both represented by the same type: System.String . However, int? and int are represented by System.Nullable<System.Int32> and System.Int32 , respectively.

Nullable reference types are a compile time feature. That means it's possible for callers to ignore warnings, intentionally use null as an argument to a method expecting a non nullable reference. Library authors should include run-time checks against null argument values. The ArgumentNullException.ThrowIfNull is the preferred option for checking a parameter against null at run time.

Enabling nullable annotations can change how Entity Framework Core determines if a data member is required. You can learn more details in the article on Entity Framework Core Fundamentals: Working with Nullable Reference Types .

Generics require detailed rules to handle T? for any type parameter T . The rules are necessarily detailed because of history and the different implementation for a nullable value type and a nullable reference type. Nullable value types are implemented using the System.Nullable<T> struct. Nullable reference types are implemented as type annotations that provide semantic rules to the compiler.

  • If the type argument for T is a reference type, T? references the corresponding nullable reference type. For example, if T is a string , then T? is a string? .
  • If the type argument for T is a value type, T? references the same value type, T . For example, if T is an int , the T? is also an int .
  • If the type argument for T is a nullable reference type, T? references that same nullable reference type. For example, if T is a string? , then T? is also a string? .
  • If the type argument for T is a nullable value type, T? references that same nullable value type. For example, if T is a int? , then T? is also a int? .

For return values, T? is equivalent to [MaybeNull]T ; for argument values, T? is equivalent to [AllowNull]T . For more information, see the article on Attributes for null-state analysis in the language reference.

You can specify different behavior using constraints :

  • The class constraint means that T must be a non-nullable reference type (for example string ). The compiler produces a warning if you use a nullable reference type, such as string? for T .
  • The class? constraint means that T must be a reference type, either non-nullable ( string ) or a nullable reference type (for example string? ). When the type parameter is a nullable reference type, such as string? , an expression of T? references that same nullable reference type, such as string? .
  • The notnull constraint means that T must be a non-nullable reference type, or a non-nullable value type. If you use a nullable reference type or a nullable value type for the type parameter, the compiler produces a warning. Furthermore, when T is a value type, the return value is that value type, not the corresponding nullable value type.

These constraints help provide more information to the compiler on how T is used. That helps when developers choose the type for T and provides better null-state analysis when an instance of the generic type is used.

Nullable contexts

For small projects, you can enable nullable reference types, fix warnings, and continue. However, for larger projects and multi-project solutions, that might generate a large number of warnings. You can use pragmas to enable nullable reference types file-by-file as you begin using nullable reference types. The new features that protect against throwing a System.NullReferenceException can be disruptive when turned on in an existing codebase:

  • All explicitly typed reference variables are interpreted as non-nullable reference types.
  • The meaning of the class constraint in generics changed to mean a non-nullable reference type.
  • New warnings are generated because of these new rules.

The nullable annotation context determines the compiler's behavior. There are four values for the nullable annotation context :

  • Nullable warnings are disabled.
  • All reference type variables are nullable reference types.
  • Use of the ? suffix to declare a nullable reference type produces a warning.
  • You can use the null forgiving operator, ! , but it has no effect.
  • All new nullable warnings are enabled.
  • You can use the ? suffix to declare a nullable reference type.
  • Reference type variables without the ? suffix are non-nullable reference types.
  • The null forgiving operator suppresses warnings for a possible dereference of null .
  • All reference type variables are allowed to be null. However, members have the null-state of not-null at the opening brace of all methods unless declared with the ? suffix.
  • You can use the null forgiving operator, ! .
  • All new nullable warnings are disabled.

The nullable annotation context and nullable warning context can be set for a project using the <Nullable> element in your .csproj file. This element configures how the compiler interprets the nullability of types and what warnings are emitted. The following table shows the allowable values and summarizes the contexts they specify.

Context Dereference warnings Assignment warnings Reference types suffix operator
Disabled Disabled All are nullable Produces a warning Has no effect
Enabled Enabled Non-nullable unless declared with Declares nullable type Suppresses warnings for possible assignment
Enabled Not applicable All are nullable, but members are considered at opening brace of methods Produces a warning Suppresses warnings for possible assignment
Disabled Disabled Non-nullable unless declared with Declares nullable type Has no effect

Reference type variables in code compiled in a disabled context are nullable-oblivious . You can assign a null literal or a maybe-null variable to a variable that is nullable-oblivious . However, the default state of a nullable-oblivious variable is not-null .

You can choose which setting is best for your project:

  • Choose disable for legacy projects that you don't want to update based on diagnostics or new features.
  • Choose warnings to determine where your code might throw System.NullReferenceException s. You can address those warnings before modifying code to enable non-nullable reference types.
  • Choose annotations to express your design intent before enabling warnings.
  • Choose enable for new projects and active projects where you want to protect against null reference exceptions.

You can also use directives to set these same contexts anywhere in your source code. These directives are most useful when you're migrating a large codebase.

  • #nullable enable : Sets the nullable annotation context and nullable warning context to enable .
  • #nullable disable : Sets the nullable annotation context and nullable warning context to disable .
  • #nullable restore : Restores the nullable annotation context and nullable warning context to the project settings.
  • #nullable disable warnings : Set the nullable warning context to disable .
  • #nullable enable warnings : Set the nullable warning context to enable .
  • #nullable restore warnings : Restores the nullable warning context to the project settings.
  • #nullable disable annotations : Set the nullable annotation context to disable .
  • #nullable enable annotations : Set the nullable annotation context to enable .
  • #nullable restore annotations : Restores the nullable annotation context to the project settings.

For any line of code, you can set any of the following combinations:

Warning context Annotation context Use
project default project default Default
enable disable Fix analysis warnings
enable project default Fix analysis warnings
project default enable Add type annotations
enable enable Code already migrated
disable enable Annotate code before fixing warnings
disable disable Adding legacy code to migrated project
project default disable Rarely
disable project default Rarely

Those nine combinations provide you with fine-grained control over the diagnostics the compiler emits for your code. You can enable more features in any area you're updating, without seeing more warnings you aren't ready to address yet.

The global nullable context does not apply for generated code files. Under either strategy, the nullable context is disabled for any source file marked as generated. This means any APIs in generated files are not annotated. There are four ways a file is marked as generated:

  • In the .editorconfig, specify generated_code = true in a section that applies to that file.
  • Put <auto-generated> or <auto-generated/> in a comment at the top of the file. It can be on any line in that comment, but the comment block must be the first element in the file.
  • Start the file name with TemporaryGeneratedFile_
  • End the file name with .designer.cs , .generated.cs , .g.cs , or .g.i.cs .

Generators can opt-in using the #nullable preprocessor directive.

By default, nullable annotation and warning contexts are disabled . That means that your existing code compiles without changes and without generating any new warnings. Beginning with .NET 6, new projects include the <Nullable>enable</Nullable> element in all project templates.

These options provide two distinct strategies to update an existing codebase to use nullable reference types.

Known pitfalls

Arrays and structs that contain reference types are known pitfalls in nullable references and the static analysis that determines null safety. In both situations, a non-nullable reference might be initialized to null , without generating warnings.

A struct that contains non-nullable reference types allows assigning default for it without any warnings. Consider the following example:

In the preceding example, there's no warning in PrintStudent(default) while the non-nullable reference types FirstName and LastName are null.

Another more common case is when you deal with generic structs. Consider the following example:

In the preceding example, the property Prop is null at run time. It's assigned to non-nullable string without any warnings.

Arrays are also a known pitfall in nullable reference types. Consider the following example that doesn't produce any warnings:

In the preceding example, the declaration of the array shows it holds non-nullable strings, while its elements are all initialized to null . Then, the variable s is assigned a null value (the first element of the array). Finally, the variable s is dereferenced causing a runtime exception.

  • Nullable reference types proposal
  • Draft nullable reference types specification
  • Unconstrained type parameter annotations
  • Intro to nullable references tutorial
  • Nullable (C# Compiler option)
  • CS8602: Possible dereference of null warning

Additional resources

How to Handle Null References in the Latest Version of C#

How to Handle Null References in the Latest Version of C#

By Zoran Horvat

C# 12 has just been released, and it continues the long tradition of improvements in the safety of the language's software design and execution.

One of these improvements relates to manipulating null references, a programming concept that many developers don't really love.

Using null references in your code can cause all kinds of issues, like exceptions and a lack of information.

This article will teach you how to cope with null references in the latest version of the C# programming language and .NET. The name of the game: let no null pass unattended.

This demonstration will have several stages, each with its own small demo. If you wish to skip through, please use the table of contents below.

Table of Contents

Prerequisites, how to use nullable reference types, how to use the is null and is not null patterns, how to use type-test-and-set patterns, how to use property patterns, how to use the null propagation and null coalescing operators.

  • How to Work with Optional Objects

Final Notes

There are a few prerequisites you will need to meet before proceeding. I assume that you've written enough C# code to see null references in their natural habitat. And I expect you to understand that they can threaten the code's design and stability.

This article will clarify these concepts and identify the issues and solutions using C# syntax and libraries.

If you are ready, we can get started with nullable reference types. That will allow us to set up the working environment and get up to speed for the more complex demos that will follow.

Nullable reference types were introduced in C# 8 and quickly became a mainstay.

The short story is that you can either declare a reference nullable (for example, string? s ) or non-nullable ( string s ).

Note the plot twist: what used to be just a reference before C# 8 ( string s was an ordinary reference to a nullable string) has now become something more: a reference that should never be set to null.

That was the breaking change, maybe the first in a decade of C# syntax evolution!

The compiler will do its best to check if all the assignments to a non-nullable reference (the one without the question mark) set it to a proper object. If it finds an execution path that might set it to null, the compiler will issue a compile-time warning. This is called "definite assignment analysis," as the compiler tries to prove that each non-nullable reference is definitely assigned to an object.

If you have already grown accustomed to nullable reference types, I have a question: would you consider not using them today? Probably not.

Let's start with some code. Below, you see two records – one deriving from another. Record types came with C# 9. I am using them here only for brevity. Consider these two types as just the base and the derived class.

We can either instantiate a record and assign the instance to a reference, or assign a reference to null.

This is where the definite assignment analysis comes to the table. If there is a sequence of instructions in which the reference ends up being null, we must use the question mark to indicate that the reference can be null.

You can see that the second reference ( bob ) is assigned to a proper object but is still declared nullable. That is perfectly fine in scenarios where an object is coming from the outside, and you might not know whether it will be there or not.

Make sure you don't assign a nullable reference to a non-nullable one, though. That would cause a compile-time warning, which you can raise to the level of compile-time error if you prefer.

It is essential to understand that nullability is not the property of the type but rather a hint given to the compiler. Nullable reference types are only used during the compile-time analysis and are never stored in the compiled type itself.

One consequence is that you cannot declare a nullable type parameter in a generic type. That wouldn't make sense because the compiler has no place to put that information in the compiled type!

But then comes a twist because we are free to indicate any reference of the generic parameter type as nullable, as in the code below. Such a reference is subject to definitive assignment analysis as any other.

We have defined the utility function to showcase all situations incorporating null references in the rest of this article. As I already pointed out, it would be a compile-time error to declare this generic function as Showcase<T?> , while accepting a nullable T? in the argument list would be perfectly valid. Makes your head spin around!

An even greater mystery is to come: why not remove nullable from the argument list? What would that mean?

That would leave it to the caller to determine nullability because – now pay attention! – a concrete generic parameter type can be nullable. It determines the nullability of references, which is a real thing during compilation.

I hope you have started to grasp these concepts more now. Unfortunately, it would take a lot of space to explain this concept in-depth, but I would certainly advise you to learn more about nullability of types. It is now part of C# and is here to stay.

Let me give you a quick demo showcasing the two possible choices:

The first call above allows null references in the arguments, while the second call forces non-nullable references. So the compiler would check the references passed as arguments in that case and raise a warning if any of them is, or could be, null.

That concludes our crash course on nullable reference types in C#. We are ready to proceed with more advanced matters.

Before that, here is the output produced by the code as we have it so far:

Pay attention to the empty line in the output. That is where we have passed null to the Console.WriteLine . The WriteLine method accepts null and treats it the same way it treats an empty string.

Once we get nullability right, we can start doing logic around it. The simplest of all operations is asking if a reference is equal to null.

The is operator is testing an object against a pattern. We'll meet this operator several more times in the upcoming sections.

In this demo, you can see its simplest use: testing against the null pattern. There are two possibilities there, is null and is not null , with the meaning that appears to require no further explanation. Oh, but that would be a big mistake!

A corner case is covered by is null and is not null patterns, which might be the core reason for introducing these patterns in the first place. Both patterns will avoid calling any overload of the == and != operators.

So, in theory, a class could overload the == and != operators and, in doing so, declare that a particular object should be considered equal to a null reference. But the is null pattern will not call the operator overload – thus, it will flatly reject comparing that same non-null object to null.

That is a minor corner case, but it teaches how C# operates under the hood. The bottom line is: you should favor is null over == , and is not null over != when testing for null/non-null.

Here is the printout produced when we run the function above on a few references, one of them being null.

The time has come to raise the bar and use some of the more complex methods of processing nullable references. We will remain with the is operator, but this time, we'll use its more potent form: testing type patterns.

Each reference in C# resolves into an object (or a lack of – a null), and each object we reference possesses the type descriptor. That is at the core of any object-oriented language.

So it's pretty easy for the .NET runtime to check whether a reference is pointing to an object – and, if so, whether that object's runtime type derives from a specific type, directly or indirectly.

That was a mouthful, wasn't it? Let's split that up into bits:

  • To test whether a reference references an actual object, that is the person is not null pattern.
  • To add the test whether that object is assignable to a particular type, we use the type pattern instead: person is Celebrity .
  • Finally, to capture the reference to the desired type and use it in subsequent statements and expressions, we use the full-blown type-test-and-set expression: person is Celebrity celeb .

These are the three stages of extracting information from a reference, each more potent than the other.

Without further ado, here is the method that exercises the most detailed form: testing against null and downcasting, all packed in one condensed expression:

You may have noticed that these expressions are effectively implementing safe downcasting. Downcasting was frowned upon for decades, accused (mostly rightfully) of causing code defects and design flaws.

But times they are a-changin'! Type test and set expressions are coming to software development from functional programming.

This article is not a place to discuss the differences between type testing and downcasting as we knew it in object-oriented languages of the past. I strongly encourage you to learn more about this intriguing topic before judging.

Here, you can see the output produced by the function above. As you can see, each actual type is captured correctly, creating its specific output. And the dreaded null was left out – I have indeed passed a null reference to the function at one instant but hadn't matched any of the patterns, and so was ignored.

This demo would be incomplete without one crucial note. The switch expression (of C# 8) is expecting patterns in order from more specific to more general ones. It would be an error to list a more specific pattern after a more general one. The general pattern would overshadow the subsequent one, never letting its right hand execute. Therefore, the switch expression like the one below causes a compile-time error in C#.

An exciting development follows if you push pattern matching even further. One specific form is the properties pattern – one aimed to match the values and attributes of properties of an object (if the object exists!).

You don't have to specify the type if you are not interested in downcasting. It will be the type of the reference to the left of the is operator.

But using the is operator implies a null test. Any reference passing the is test will be non-null and safe to check its property values on the right-hand side of the expression.

Therefore, we read this if instruction's condition as follows: If person is not null, and its property FirstName has a value Bob, then...

Here is the output produced when we call the function above:

So far, we have been doing things to objects, which is awkward in an object-oriented design. Remember, in object-oriented programming, it is the object that exposes behavior, and, as the object's users, we only make calls to its methods.

The problems still come when the reference we expect to point to an object is nullable. Making an unguarded call on the null reference was the primary source of defects. But now, with nullable references and definite assignment checks done for us, we should be safe from the dreaded NullReferenceExceptions .

Consider having a method exposed by the class. We can use ToString as a simple example.

There is a substantial difference between calling ToString on Person and on Person? types. The latter one is nullable, and therefore an unguarded call might cause dereferencing a null reference, leading to a dreaded NullReferenceException , as you can imagine.

Enter the null-propagation operator ( ?. )! We can safely make an optional call to a method, provided the reference is non-null.

But observe the consequences. If the method returns void , the call will be ignored on a null reference. If the method returns a type, then the result will be the nullable version of that type. You cannot expect a string from ToString on a nullable reference, you see? The compiler can only promise a nullable string instead.

And what if we really wanted a string, a true one? Enter the null-coalescing operator ( ?? )! We can easily convert a nullable reference to a non-nullable one by supplying a default to take when the actual value is null at run time.

In this example, we make an optional call to the ToString method first but then short-circuit the result to an empty string if the reference were null. The result is that any null reference would produce an empty string for printout.

How to Work With Optional Objects

The last method of addressing nulls in this article will actually not use nulls. Another riddle! The idea is to avoid nulls altogether by modeling the objects as possibly missing. Mind the word "possibly" – that will become part of the type declaration the same way nullability was.

If you are new to optional objects, then this short explanation will be anything but sufficient to learn about them. C# has no native support for optional objects. You can choose one of the many implementations available on NuGet, the most popular one being the LanguageExt library.

An optional object of some type is an object that either exists or does not exist. Whichever the case, the optional object itself will always exist. Another riddle for you to solve!

Here is how we would declare a few optional objects:

The two shapes of an optional object are usually referred to as None and Some . The Some variant must contain an actual object. That completes the creation of optional objects and the code that will never have a null reference.

But what is the difference compared to nullable references? Why should we use optional objects at all?

The short story is that optional objects let us apply functions to the optional object's content – if present. The optional object will either invoke the function and pass the content to it or skip calling it altogether if there is no content.

Therefore, an optional type is a single place where that calling protocol is now implemented, the protocol in many ways equivalent to safely dereferencing nullable references.

The Match method covers both possibilities: It either maps the Person object to a string or substitutes an empty string if the person is missing. The Do method will only pass content to the console if content exists.

Here is the printout produced by the Do method:

You will only see the Some variants printed out. The only missing object in the input array has produced no output because that optional instance has ignored the action passed to its Do method.

The most significant benefit of using optional objects over nullable references is their ability to apply other functions. We might already have many different classes and methods implemented in our codebase, all methods working on non-nullable references. Optional objects can bridge the gap between potentially missing objects and the common methods that are only operational when nothing is missing.

In this tutorial, we started by declaring nullable objects and testing their existence using the is operator.

Then, we extended the example by displaying the richness of pattern-matching expressions: type test and set and property pattern expressions.

We then moved the focus from consuming objects to calling their behavior from the null-propagation operator over the null-coalescing operator, landing in the vast field of functional programming and optional objects.

I hope you enjoyed the ride. In place of farewell, I will invite you to learn more about optional objects in C# by watching my recent video How to Avoid Null Reference Exceptions: Optional Objects in C# .[

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • Essential C#
  • Announcements

As described in Chapter 3, while null can be a useful value, it also comes with a few challenges—namely, the need to check a value isn’t null before invoking the object’s member or changing the value from null to something more appropriate to the circumstance.

Although you can check for null using the equality operators and even the relational equality operators, there are several other ways to do so, including C# 7.0’s support for is null and C# 10.0’s support for is not null . In addition, several operators are designed exclusively for working with the potential of a null value. These include the null-coalescing operator (and C# 8.0’s null-coalescing assignment) and the null-conditional operator. There is even an operator to tell the compiler when you believe a value isn’t null even if it isn’t obvious to the compiler—the null-forgiving operator. Let’s start by simply checking whether a value is null or not.

It turns out there are multiple ways to check for null , as shown in Table 4.4 . For each listing, assume a declaration of string? uriString precedes it:

string ? uriString = null ;

Description

Example

is null Operator Pattern Matching

The is operator provides multiple approaches to check for null. Starting with C# 7.0, you can check whether a value is null using the is null expression. This is a succinct and clear approach to checking if a value is null.

// 1.

if (uriString is null)

{

     Console.WriteLine(

         "Uri is null");

}

is not null Operator Pattern Matching

Similarly, in C# 9.0, is not null support was added. And, when checking for not null, this is the preferred approach.

// 2.

if (uriString is not null)

{

     Console.WriteLine(

         "Uri is not null");

}

Equality/Inequality

Using the equality and inequality operators works with all versions of C#.

In addition, checking for null this way is readable.

The only disadvantage of this approach is that it is possible to override the equality/inequality operator, potentially introducing minor performance impacts.

// 3.

if(uriString == null)

{

     Console.WriteLine(

         "Uri is null");

}

if(uriString != null)

{

     Console.WriteLine(

         $"Uri is: { uriString }");

}

is object

Since C# 1.0, is object checks whether the operand is null, although this syntax isn’t as clear as is not null.

is object is preferable over the is {} expression described in the next row because it issues a warning when the operand is a non-nullable value type. What is the point in checking for null if the operand can’t be null?

// 4.

int number = 0;

if( (uriString is object )

     // Warning CS0183: The given

     // expression is always not

     // null.

     && (number is object)

)

{

     Console.WriteLine(

         $"Uri is: { uriString }");

}

is { } Operator Pattern Matching

The property pattern matching expression, <operand> is { }, (which was added in C# 8.0) provides virtually the same functionality as is object. Besides being less readable, the only noticeable disadvantage is that is {} with a value type expression doesn’t issue a warning, while is object does. And, since a value type cannot be null, the warning is preferable because there is no point in checking a non-nullable value for null. Therefore, favor using is object over is { },

// 5.

if (uriString is {})

{

     Console.WriteLine(

         $"Uri is: { uriString }");

}

ReferenceEquals()

While object.ReferenceEquals() is a somewhat long syntax for such a simple operation, like equality/inequality it works with all versions of C# and has the advantage of not allowing overriding; thus, it always executes what the name states.

// 6.

if(ReferenceEquals(

   uriString, null))

{

     Console.WriteLine(

         "Uri is null");

}

Of course, having multiple ways to check whether a value is null raises the question as to which one to use. C# 7.0’s enhanced is null and C# 9.0’s is not null syntax are preferable if you are using a modern version of C#.

Obviously, if you are programming with C# 6.0 or earlier, the equality/inequality operators are the only option aside from using is object to check for not null . The latter has a slight advantage since it is not possible to change the definition of the is object expression and (albeit unlikely) introduce a minor performance hit. This renders is {} effectively obsolete. Using ReferenceEquals() is rare, but it does allow comparison of values that are of unknown data types, which is helpful when implementing a custom version of the equality operator (see “ Operator Overloading ” in Chapter 10).

Several of the rows in Table 4.4 leverage pattern matching, a concept covered in more detail in the “ Pattern Matching ” section of Chapter 7.

The null-coalescing operator is a concise way to express “If this value is null , then use this other value.” It has the following form:

expression1 ?? expression2

The null-coalescing operator also uses a form of short-circuiting. If expression1 is not null , its value is the result of the operation and the other expression is not evaluated. If expression1 does evaluate to null , the value of expression2 is the result of the operator. Unlike the conditional operator, the null-coalescing operator is a binary operator.

Listing 4.37 illustrates the use of the null-coalescing operator.

In this listing, we use the null-coalescing operator to set fileName to "config.json" if GetFileName() is null . If GetFileName() is not null , fileName is simply assigned the value of GetFileName() .

The null-coalescing operator “chains” nicely. For example, an expression of the form x ?? y ?? z results in x if x is not null ; otherwise, it results in y if y is not null ; otherwise, it results in z . That is, it goes from left to right and picks out the first non- null expression, or uses the last expression if all the previous expressions were null . The assignment of directory in Listing 4.37 provides an example.

C# 8.0 provides a combination of the null-coalescing operator and the assignment operator with the addition of the null-coalescing assignment operator . With this operator, you can evaluate if the left-hand side is null and assign the value on the righthand side if it is. Listing 4.37 uses this operator when assigning fullName .

In recognition of the frequency of the pattern of checking for null before invoking a member, you can use the ?. operator, known as the null-conditional operator , 4 as shown in Listing 4.38 . 5

The null-conditional operator example ( int? length = segments?.Length ) checks whether the operand (the segments in Listing 4.38 ) is null prior to invoking the method or property (in this case, Length ). The logically equivalent explicit code would be the following (although in the original syntax, the value of segments is evaluated only once):

int ? length =

     (segments != null ) ? (int?)segments.Length : null

An important thing to note about the null-conditional operator is that it always produces a nullable value. In this example, even though the string.Length member produces a non-nullable int , invoking Length with the null-conditional operator produces a nullable int ( int? ).

You can also use the null-conditional operator with the array accessor. For example, uriString = segments?[0] produces the first element of the segments array if the segments array was not null . Using the array accessor version of the null-conditional operator is relatively rare, however, as it is only useful when you don’t know whether the operand is null , but you do know the number of elements, or at least whether a particular element exists.

What makes the null-conditional operator especially convenient is that it can be chained (with and without more null-coalescing operators). For example, in the following code, both ToLower() and StartWith() will be invoked only if both segments and segments[0] are not null :

segments?[0]?.ToLower().StartsWith( "file:" );

In this example, of course, we assume that the elements in segments could potentially be null , so the declaration (assuming C# 8.0) would more accurately have been

string ?[]? segments;

The segments array is nullable, in other words, and each of its elements is a nullable string.

When null-conditional expressions are chained, if the first operand is null , the expression evaluation is short-circuited, and no further invocation within the expression call chain will occur. You can also chain a null-coalescing operator at the end of the expression so that if the operand is null , you can specify which default value to use:

string uriString = segments?[0]?.ToLower().StartsWith(

     "file:" ) ?? "intellitect.com" ;

Notice that the data type resulting from the null-coalescing operator is not nullable (assuming the right-hand side of the operator [ "intellitect.com" in this example] is not null —which would make little sense).

Be careful, however, that you don’t unintentionally neglect additional null values. Consider, for example, what would happen if ToLower() (hypothetically, in this case) returned null . In this scenario, a NullReferenceException would occur upon invocation of StartsWith() . This doesn’t mean you must use a chain of null-conditional operators, but rather that you should be intentional about the logic. In this example, because ToLower() can never be null , no additional null-conditional operator is necessary.

Although perhaps a little peculiar (in comparison to other operator behavior), the return of a nullable value type is produced only at the end of the call chain. Consequently, calling the dot ( . ) operator on Length allows invocation of only int (not int? ) members. However, encapsulating segments?.Length in parentheses—thereby forcing the int? result via parentheses operator precedence—will invoke the int? return and make the Nullable<T> specific members ( HasValue and Value ) available. In other words, segments?.Length.Value won’t compile because int (the data type returned by Length ) doesn’t have a member called Value . However, changing the order of precedence using (segments?.Length).Value will resolve the compiler error because the return of (segments?.Length) is int? , so the Value property is available.

Notice that the Join() invocation of Listing 4.38 includes an exclamation point after segments :

uriString = string .Join( '/' , segments ! );

At this point in the code, segments?.Length is assigned to the length variable, and since the if statement verifies that length is not null , we know that segments can’t be null either.

int ? length = segments?.Length;

if (length is not null && length != 0){ }

However, the compiler doesn’t have the capability to make the same determination. And, since Join() requires a non-nullable string array, it issues a warning when passing an unmodified segments variable whose declaration was nullable. To avoid the warning, we can add the null-forgiving operator ( ! ), starting in C# 8.0. It declares to the compiler that we, as the programmer, know better, and that the segments variable is not null . Then, at compile time, the compiler assumes we know better and dismisses the warning (although the runtime still checks that our assertion is not null at execution time).

Note that while the null-conditional operator checks that segments isn’t null, it doesn’t check how many elements there are or check that each element isn’t null.

In Chapter 1 we encountered warning CS8600, “Converting null literal or possible null value to non-nullable type,” when assigning Console.ReadLine() to a string . The occurs because Console.ReadLine() returns a string? rather than a non-nullable string . In reality, Console.ReadLine() returns null only if the input is redirected, which isn’t a use case we are expecting in these intro programs, but the compiler doesn’t know that. To avoid the warning, we could use the null-forgiving operator on the Console.ReadLine() return—stating we know better that the value returned won’t be null (and if it is, we are comfortable throwing a null-reference exception).

string text = Console.ReadLine() ! ;

The null-conditional operator is a great feature on its own. However, using it in combination with a delegate invocation resolves a C# pain point that has existed since C# 1.0. Notice in Listing 4.39 how the PropertyChanged event handler is assigned to a local copy ( propertyChanged ) before we check the value for null and finally fire the event. This is the easiest thread-safe way to invoke events without running the risk that an event unsubscribe will occur between the time when the check for null occurs and the time when the event is fired. Unfortunately, this approach is nonintuitive, and frequently developers neglect to follow this pattern—with the result of throwing inconsistent NullReferenceExceptions . Fortunately, with the introduction of the null-conditional operator, this issue has been resolved.

The check for a delegate value changes from what is shown in Listing 4.39 to simply

PropertyChanged?.Invoke(propertyChanged(

   this , new PropertyChangedEventArgs(nameof(Age)));

Because an event is just a delegate, the same pattern of invoking a delegate via the null-conditional operator and an Invoke() is always possible.

________________________________________

  • p.key == item.key) && !currentPage.some(p => p.level > item.level), }" > p.key == item.key) && !currentPage.some(p => p.level > item.level), }" :href="item.href"> Introduction
  • p.key == item.key) && !currentPage.some(p => p.level > item.level), }" > p.key == item.key), }" :href="item.href"> {{item.title}}

C# Corner

  • TECHNOLOGIES
  • An Interview Question

C#

Null-Coalescing Assignment Operator In C# 8.0

assignment null c#

  • Habibul Rehman
  • Oct 17, 2023
  • Other Artcile

In this article, we will learn how to use Null-coalescing assignment operator in C# and also check the updated requirements of Null-coalescing operator requirements.

Introduction

C# 8.0 introduces the null-coalescing assignment operator ??=. You can use the ??= operator to assign the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null. In C# 7.3, the null-coalescing operator ?? also had a few requirements that are now required in C# 8.0. We will discuss this also in detail.

Prerequisites

To use the Null-coalescing assignment operator ??=, you'll need to set up your machine to run .NET Core, including the C# 8.0 compiler. The C# 8 compiler is available starting with Visual Studio 2019 version 16.3 or .NET Core 3.0 SDK .

Let's Start

Use null-coalescing assignment operator ??= to assign the value of the right-hand side operand to the left-hand side operand only if the left-hand side operand evaluates to null.

For instance, in the below-given code, I'm initializing a List of int named "numbers" with the null reference. Then I'm using the Null-coalescing assignment operator to assign a new List of int if " the number; value is null.

In previous versions of C# like 7.3, we were using other techniques to do the same task as performed by the Null-coalescing assignment operator??. For instance, I'm using the Null-coalescing operator to do the same, but it seems a little bit cheap.

Null-coalescing operator updated requirements

In C# 7.3 and earlier, the type of the left-hand operand of the ?? operator must be either a reference type or a nullable value type . Beginning with C# 8.0, that requirement is replaced with the following: the type of the left-hand operand of the ?? and ??= operators cannot be a non-nullable value type, for instance.

In particular, beginning with C# 8.0, you can use the null-coalescing operators with unconstrained type parameters. For instance, I'm using a Null-coalescing operator with a non-nullable type, and it gives the error.

So when I tried to build this, it gave an error.

ErrorCS0019Operator '??' cannot be applied to operands of type 'int' and 'int'

For more new features of C# 8.0, please see MS Docs.

  • .NET Framework
  • Null-coalescing
  • C# Features

C# Corner Ebook

Pattern Matching in C#

assignment null c#

C#: Different ways to Check for Null

What is the classic way to check if for example a parameter value is null ? If you’ve developed with C# since a while, you might be familiar with this classic syntax:

Since C# version 7 you can use the is keyword for the null check like in the snippet below:

But with C# 7, there’s even a shorter syntax. Discards were also introduced. They are unused and ignored variables that are represented in your code with an underscore (_). In combination with the Null-coalescing operator (??) you can write the null check like this:

That means, the whole method looks just like this:

To be honest, I really like the last approach using the discards, but maybe for some developers it’s too much. I think the is keyword is very clear and readable. It is my favorite.

The is keyword has also the big advantage that it ignores any ==/!= operator overloads on the specific class. It will do a null check, no matter if there’s an operator overload or not. That makes it better than just using ==. You can read more about this in this blog post .

The Is Keyword And the Not Pattern in C# 9.0

With C# 9.0, you can combine the is expression with the logical not pattern, which is powerful if you want to check if an object is NOT null. Before C# 9.0 you had to use the is expression like below to check if an object is not null:

Some developers preferred the following syntax to check if the name is not null:

But the statements above are neither very readable nor easy to understand. That’s why many developers still prefer the classic way:

But since C# 9.0, you can write that not null check like below, and I think that is really readable code:

So, with C# 9.0, you can write your null / not-nulll checks like below, and I think that’s readable:

Happy coding, Thomas

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Share this post

' src=

Thomas Claudius Huber

Comments (27)

[…] C#: Different ways to Check for Null (Thomas Claudius Huber) […]

' src=

When you want to check for not-null, you can do..

if (foo != null) if (!(foo is null)) if (foo is object)

I prefer the third because it’s clear and concise and doesn’t involve negation or nested parens.

yes, that’s super cool. I really like “foo is object”, but I guess it’s not as obvious as !(foo is null)

Best would be

if(foo is not null)

But we don’t have that (yet?).

' src=

also if(foo is { })

[…] C#: Different ways to Check for Null – Thomas Claudius Huber […]

' src=

Good use of _ = name ?? throw new ArgumentNullException(nameof(name));

it’s sensible and neat

Thanks Dipo. :)

Yes, it is. I like it too.

' src=

I like the ’is’ variant. Hopefully, with the nullable reference types introduced in C#8 we’ll be able to get rid of null-guards like these. If there is a need to represent the possible abscence of a value I prefer the Option type. I wrote a blog post on this topic that you might find interesting, see https://ericbackhage.net/c/nullable-reference-types-compared-to-the-option-monad/

yes, with nullable reference types we should be able to reduce these null-guards in our code.

Thank you for sharing that blog post, it’s a great read! Thomas

' src=

Unfortunately all NRTs bring to the table are compile-time checks that you are putting your null-guards in :)

Thanks for the post Thomas. A quick update for those coming across this article at a later date.

The new C# 9 patterns will bring ‘is not null’, yay! ( https://github.com/dotnet/csharplang/blob/master/proposals/csharp-9.0/patterns3.md#pattern-combinators ).

But we’ll have to wait and see whether Simplified Null Argument Checking will make it into a release https://github.com/dotnet/csharplang/blob/master/proposals/null-arg-checking.md .

Thank you Ben, the new C# 9 patterns are really a great addition to the language.

' src=

Thanks Thomas. I had the following piece of code that does a null check within a Ternary Expression:

private static string GetAttributeValue(Assembly assembly) where T : Attribute { var type = typeof(T); var attribute = assembly .CustomAttributes .Where(x => x.AttributeType == type) .Select(x => x.ConstructorArguments.FirstOrDefault()) .FirstOrDefault(); return attribute == null ? string.Empty : attribute.Value?.ToString(); }

When I updated this to change the line that was attempting a null check to

return attribute is null ? string.Empty : attribute.Value?.ToString();

The compiler explained to me that I am trying to do a null check against a non-nullable value type. By attempting this, I realized the null check was not necessary after confirming the type System.Reflection.CustomAttributeTypedArgument is a non-nullable struct.

So the offending line can be simplified to

return attribute.Value?.ToString();

And this can be simplified to

return attribute.Value.ToString();

Since System.Reflection.CustomAttributeTypedArgument.Value cannot be null.

Does this seem accurate to you? Point of sharing this is to demonstrate after going through a code base to update null checks, I learned something the code was doing that is not necessary: a null check against a non-nullable value type.

Hey Jamie, yes, your adjustments looks accurate to me. I see a lot of code that does null checks against value types that can not be null. :-) Usually you find these also in the warnings of the compiler.

' src=

You’re welcome! Thank you Avi.

' src=

In C# 9.0 you can also test for not null with an empty property pattern. This is useful when you want to assign the result to a variable `if (GetValue() is { } value)`. (But `is not null value` does not compile).

Interesting. Seems to be a shortcut for if (GetValue() is [variabletype] value)

' src=

OHHHH you need c# 9.0 for the “is not null” keywords to work.

I was wondering why it was giving me weird results on my Unity project.

Thanks for your insight. Cheers

Hi Tony, excactly. C# 9.0 rocks it. :)

' src=

Another interesting way (not null): if (value is { })

Absolutely, that one is great too. :-)

' src=

> The is keyword has also the big advantage that it ignores any ==/!= operator overloads on the specific class. It will do a null check, no matter if there’s an operator overload or not.

Bill Gates once said in an interview that he envied Steve Jobs’ taste for choosing simple solutions. Bill Gates hasn’t been running Microsoft for a long time, and certainly not .NET development. But I see that his followers have inherited the same traits.

' src=

Hi Thanks for the article. When I do this:

Student jewll = new student();

I noticed that jewell is NOT NULL, and since it does not have a value, what does it contain? How could I tell it was never had any of its properties assigned a value since it was created? Thanks.

' src=

ArgumentNullException.ThrowIfNull(validateMe, nameof(validateMe));

' src=

Hi Thanks for the article. I have seen null == name been used too, Is it somehow better than any other cases

That’s OK too, and it’s the original syntax to check for null in C# (and still valid!)

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Spam protection: Sum of 1 + 5 ? *

Notify me of follow-up comments by email.

Notify me of new posts by email.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Related Posts

C# 12: default parameters in lambda expressions.

In the previous blog posts of this C# 12 series you learned about different C# 12 features: Primary Constructors Collection Expressions Alias Any... read more

C# 12: Alias Any Type

In the previous blog posts of this C# 12 series you learned about different C# 12 features: Primary Constructors Collection Expressions In this... read more

C# 12: Collection Expressions

In the previous blog post you learned about C# 12 primary constructors. In this blog post, you will learn about... read more

C# 12: Primary Constructors

In November 2023, Microsoft released .NET 8.0, and since then you can use C# 12.So, it might be a good... read more

Create a GitHub Action in Visual Studio to Deploy Your .NET Web App automatically to Azure on Every Commit

When building a web application, it can be helpful to deploy your application with the latest features and code changes... read more

C# 11.0: Generic Math, C# Operators and Static Abstract/Virtual Interface Members

In the previous blog posts you learned about different C# 11.0 features: Raw String Literals Generic Attributes In this blog post, let's look... read more

C# 11.0: Generic Attributes

In the previous blog post you learned about C# 11.0 raw string literals. In this blog post, you will learn about another... read more

C# 11.0: Raw String Literals

In November 2022, .NET 7.0 was released, and since then, you can use C# 11.0. In version 11.0, the C# language... read more

C# 10.0: Extended Property Patterns – Use the Dot Token to Access Nested Members

In the previous blog posts you learned about different C# 10.0 features: File-scoped namespaces Global using directives In this blog post, let's look... read more

C# 10.0: Global Using Directives – Make Important Namespaces Available in Your Whole Project

In the previous blog post you learned about C# 10.0 file-scoped namespaces. In this blog post you learn about another C# 10.0... read more

IMAGES

  1. Null-Coalescing Assignment Operator ??=

    assignment null c#

  2. Null-Coalescing Assignment Operator ??=

    assignment null c#

  3. Null-Coalescing Assignment Operator (??=) in C#

    assignment null c#

  4. C# Null Assignment Operator

    assignment null c#

  5. C# Highlights

    assignment null c#

  6. C# Programmers FAQ

    assignment null c#

VIDEO

  1. ASSIGNMENT 4: C# Scripting

  2. How to check Null values in C#

  3. Solved: hostingenvironment.WebRootPath is null in Asp.Net 7+ WebApi

  4. C Assignment multiplication operator #short #c#assignment #multiplication #operator #printf #coding

  5. Embedded C ++ Interview Questions

  6. Dynamic Dispatch

COMMENTS

  1. c# - Shortest way to check for null and assign another value ...

    To assign a non-empty variable without repeating the actual variable name (and without assigning anything if variable is null!), you can use a little helper method with a Action parameter: public static void CallIfNonEmpty(string value, Action<string> action) { if (!string.IsNullOrEmpty(value)) action(value); }

  2. ?? and ??= operators - null-coalescing operators - C# reference

    The null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null. The ??= operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

  3. .net - How to set null value to int in c#? - Stack Overflow

    In .Net, you cannot assign a null value to an int or any other struct. Instead, use a Nullable<int> , or int? for short: int? value = 0; if (value == 0) { value = null; }

  4. Null Operators and Handling Null Values in C# - Medium

    C# provides three operators to make it easier to work with nulls: the null-coalescing operator, the null-coalescing assignment operator, and the null-conditional operator.

  5. Nullable reference types - C# | Microsoft Learn

    You can assign a null literal or a maybe-null variable to a variable that is nullable-oblivious. However, the default state of a nullable-oblivious variable is not-null . You can choose which setting is best for your project:

  6. How to Handle Null References in the Latest Version of C#

    This article will teach you how to cope with null references in the latest version of the C# programming language and .NET. The name of the game: let no null pass unattended. This demonstration will have several stages, each with its own small demo.

  7. Essential C#: Programming with null

    C# 8.0 provides a combination of the null-coalescing operator and the assignment operator with the addition of the null-coalescing assignment operator. With this operator, you can evaluate if the left-hand side is null and assign the value on the righthand side if it is.

  8. Null-Coalescing Assignment Operator In C# 8.0 - C# Corner

    C# 8.0 introduces the null-coalescing assignment operator ??=. You can use the ??= operator to assign the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null.

  9. C#: Different ways to Check for Null – Thomas Claudius Huber

    C#: Different ways to Check for Null. By Thomas Claudius Huber .NET, C# 27 Comments. What is the classic way to check if for example a parameter value is null? If you’ve developed with C# since a while, you might be familiar with this classic syntax: public static int CountNumberOfSInName(string name) . { if (name == null) {

  10. C#'s null-coalescing operator (??) explained - Kodify">C#'s null-coalescing operator (??) explained - Kodify

    C#’s null-coalescing operator (??) works on two values and has the following pattern: valueA ?? valueB. The operator evaluates its first value to see whether it’s non-null. When it is, the operator returns that value. Else the null-coalescing operator returns its second value.