The Guid struct is a value type in C# and has a default value of all zeroes, which represents an empty Guid. To represent the absence of a value, you can assign a null value to a Guid variable using the nullable type syntax.

Here is an example of declaring a nullable Guid variable:

Guid? nullableGuid = null;

In this case, the nullableGuid the variable is declared as a nullable Guid by appending a ? to the Guid type. This allows the variable to accept a null value, in addition to any valid Guid value.

You can also check if a Guid the variable is null using the Nullable<T>.HasValue property or the null-coalescing operator (??).

Example Program to Implement Nullable Guid in C#

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Declare a nullable Guid variable
            Guid? nullableGuid = null;

            // Prompt the user to enter a Guid
            Console.Write("Enter a Guid (or press enter to skip): ");
            string input = Console.ReadLine();

            // Try to parse the input as a Guid
            if (!string.IsNullOrEmpty(input))
            {
                Guid guid;
                if (Guid.TryParse(input, out guid))
                {
                    nullableGuid = guid;
                }
                else
                {
                    Console.WriteLine("Invalid Guid format.");
                    Console.ReadKey();
                    return;
                }
            }

            // Display the entered Guid, if any
            if (nullableGuid.HasValue)
            {
                Console.WriteLine("Entered Guid: " + nullableGuid.Value);
            }
            else
            {
                Console.WriteLine("No Guid was entered.");
            }

            // Wait for the user to press a key before closing the console
            Console.ReadKey();
        }
    }
}

0 0 votes
Article Rating
Subscribe
Notify of
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback
25 days ago

[…] Web API and ASP.NET Core are both frameworks for building web applications in C#. And, If you are a .Net Developer and being involved in the Microsoft tech stack for a long. You […]