Search code examples
c#.net

Getting 'Data is Null' error when accessing database fields in C#- why "?" works and if statement doesnt


I was trying to access the data:

1   DrugName    Paracetamolum   Coffeinum   NULL    NULL

with fields..

id-ProductName -Substance1...

heres the model:

namespace Pharma;


public partial class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string Substance1 { get; set; }
    public string Substance2 { get; set; }
    public string Substance3 { get; set; }
    public string Substance4 { get; set; }



    // constructor
    public Product()
    {
        // ProductName ??= "";
        // Substance1 ??= "";
        // Substance2 ??= "";
        // Substance3 ??= "";
        // Substance4 ??= "";

        if (ProductName == null)
        {
            ProductName = "";
        }
        if (Substance1 == null)
        {
            Substance1 = "";
        }
        if (Substance2 == null)
        {
            Substance2 = "";
        }
        if (Substance3 == null)
        {
            Substance3 = "";
        }
        if (Substance4 == null)
        {
            Substance4 = "";
        }
    }
}

i got Data is Null error. Then i modyfied the fields:

   public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string? Substance1 { get; set; }
    public string? Substance2 { get; set; }
    public string? Substance3 { get; set; }
    public string? Substance4 { get; set; }

by addding "?" and then it works. But why doesnt this ifs didnt work:

if (Substance4 == null)
            {
                Substance4 = "";
            }

Im trying to understand the way .Net works and i got a question. Why adding "?" worked but if statement doesnt worked?


Solution

  • The Question Mark (?) in your property is an indication that it is a nullable tyoe. Meaning that:- It defaults to NULL value and the properties are now initialized with null before your constructor runs.

    In programming language like C# (which follows a strict approach),is to ensure that there are less compile time and runtime errors in your code. You must initialize a property/variable before you use it. In the earlier case, you declared the properties but did not assign values. When you used (?), it defaults to NULL value which is a valid value in C#.