Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

C# Tutorial

C# HOME C# Intro C# Get Started C# Syntax C# Output C# Comments C# Variables C# Data Types C# Type Casting C# User Input C# Operators C# Math C# Strings C# Booleans C# If...Else C# Switch C# While Loop C# For Loop C# Break/Continue C# Arrays

C# Methods

C# Methods C# Method Parameters C# Method Overloading C# Scope C# Recursion

C# Classes

C# OOP C# Classes/Objects C# Class Members C# Constructors C# this Keyword C# Access Modifiers C# Properties C# Static C# Inheritance C# Polymorphism C# Abstraction C# Interface C# Enums C# Structs

C# Errors

C# Errors C# Debugging C# Exceptions

C# Data Structures

C# Data Structures C# List C# Dictionary C# HashSet C# Stack C# Queue

C# Advanced

C# Files C# Date and Time C# Nullable Types C# Generics C# Lambda C# LINQ

C# Cert

C# Certificate

C# How To

C# How Tos

C# Examples

C# Examples C# Compiler C# Exercises C# Quiz C# Practice Problems C# Server C# Syllabus C# Study Plan


C# Nullable Types


Share

Nullable Types

An int variable always has a value. But sometimes a value is unknown. For example, a new player in a game has no score yet.

You could use 0 for "no score". But 0 is also a real score: the player played and got zero points.

In C#, null means "no value". But a normal int cannot be null:

Example

int score = null;
Console.WriteLine(score);

The compiler shows an error like this:

prog.cs(9,19): error CS0037: Cannot convert null to `int' because it is a value type

Try it Yourself »

To allow null, add a question mark ? after the type. This is called a nullable type:

Example

int? score = null;
Console.WriteLine(score == null);  // True

score = 25;
Console.WriteLine(score);          // 25

Try it Yourself »

int? can store any int value, or null. You can add ? to other types too, like double? and bool?.


HasValue and Value

A nullable variable has two useful properties:

  • HasValue is true if the variable has a value, and false if it is null
  • Value gives you the value

In this example, the ShowScore() method uses HasValue to check if the player has a score:

Example

static void ShowScore(int? score)
{
  if (score.HasValue)
  {
    Console.WriteLine("Score: " + score.Value);
  }
  else
  {
    Console.WriteLine("No score yet");
  }
}

static void Main(string[] args)
{
  ShowScore(25);
  ShowScore(null);
}

Try it Yourself »



Give a Default Value With ??

Often you want a normal value to work with, even when the variable is null.

The ?? operator gives a default value. It uses the value on the left if it is not null. If it is null, it uses the value on the right:

Example

int? score = null;
int points = score ?? 0;
Console.WriteLine(points);  // 0

score = 25;
points = score ?? 0;
Console.WriteLine(points);  // 25

Try it Yourself »

The first time, score is null, so points gets 0. The second time, points gets the score, 25.

The GetValueOrDefault() method works in a similar way. With empty parentheses, it uses 0 for an int. You can also write the default value inside the parentheses:

Example

int? score = null;
Console.WriteLine(score.GetValueOrDefault());    // 0
Console.WriteLine(score.GetValueOrDefault(10));  // 10

Try it Yourself »


Null Strings

A string can also be null, without a question mark. For example, a player may not have chosen a name yet.

The ?? operator works with strings too:

Example

string name = null;
Console.WriteLine(name ?? "Guest");  // Guest

name = "Liam";
Console.WriteLine(name ?? "Guest");  // Liam

Try it Yourself »

If you use a property of a null string, like name.Length, the program stops with an error (a NullReferenceException).

To avoid the error, write ?. instead of a dot. If name is null, name?.Length gives null instead of an error:

Example

string name = null;
int? length = name?.Length;
Console.WriteLine(length.HasValue);  // False

name = "Liam";
length = name?.Length;
Console.WriteLine(length.Value);     // 4

Try it Yourself »

The result of name?.Length can be null, so it is stored in an int?. To get a normal int, combine ?. with ??:

Example

string name = null;
int length = name?.Length ?? 0;
Console.WriteLine(length);  // 0

Try it Yourself »



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.