Question Compiler Error: CS8625 - Cannot convert null literal to non-nullable reference type.

ansraj91

New member
Joined
Oct 1, 2023
Messages
1
Programming Experience
3-5
The below code logically correct but why Visual Studio code is giving compiler errors:

C# Code block giving compilere error:
abstract class Test<A,B> {

   private  Test<B,object> t1;

    public Test(Test<B, object> t) {
        t1 = t;
    }

}

class Child1 : Test<int, string>
{
    public Child1(Test<string, object> t) : base(t)
    {

    }
}


class Child2 : Test<string,bool>
{
    public Child2(Test<bool, object> t) : base(t)
    {

    }
}

class Achild1
{

    public Achild1(object obj)
    {

    }
}




class Main
{
    public void Init()
    {
        Child2 c2 = new Child2(null);
        Child1 c1 = new Child1(c2);
    }

}
 
Perhaps you could point out exactly what line the error is generated on. Making each of us who want to help spend time working out things that you already know is counterproductive.
 
As general advice though, .NET 6 introduced nullable reference types, so code you used before with null values may no longer work. Previously, this was OK:
C#:
string str1 = "Hello World";
string str2 = null;
Up to .NET 5, a reference-type variable could have a value or be null. That is still possible in .NET 6 and later if you disable nullable reference types for the project, but that is not done by default. With nullable reference types enabled, you have to specify that a variable is nullable if you want it to be able to be null:
C#:
string str1 = "Hello World";
string? str2 = null;
The syntax is the same as for nullable value types, so it's easy from that perspective. Basically, you need to think about whether it makes sense that a variable be null and declare it as nullable if it does. This will prevent NullReferenceExceptions being thrown by preventing variables that should never be null from ever being null by mistake. Like many new paradigms, it takes a bit of getting used to and seems a pain at first, but it becomes second nature after a while. What can be painful is developing projects for multiple .NET versions and switching back and forth from one to the other.
 
In your case, you haven't declared anything - parameters or fields - as being nullable but you pass null explicitly, so that would not be allowed. The parameter you pass the argument to is not nullable and neither is the field that would ultimately be set to null. That code would work OK in .NET 5 but not in .NET 6 and later unless you disable nullable types, which you probably shouldn't do.
 
That code would work OK in .NET 5 but not in .NET 6 and later unless you disable nullable types, which you probably shouldn't do.

Some people like riding motorcycles without helmets, or riding in cars without seatbelts. :)
 
Back
Top Bottom