How to initialize a variable of type Interface as empty?

Elad

Member
Joined
Feb 15, 2020
Messages
19
Programming Experience
1-3
Hello! I wanted to know how to send to a function that accepts a particular interface as null or at least as an empty variable? Here is the code:
   public Package(Priority priority, Address senderAddress, Address destinationAdress)
        {
            PackageID = count++;
            Priority = priority;
            Tracking = new List<Tracking>();
            SenderAddress = senderAddress;
            DestinationAddress = destinationAdress;
             //The null is painted green,
            AddTracking(null);
          
        }

        public void AddTracking(INode node, Status status = Status.CREATION)
        {
            Tracking.Add(new Tracking(MainOffice.Clock, node, status));
        }
//And Interface
    public interface INode
    {
        void CollectPackage(Package pack);
        void DeliverPackage(Package pack);
        string GetName();
        void Work();
    }

I get such a warning "Cannot convert null literal to non-nullable reference type."
By the way in java interface can be set to null why in c # it does not work in this logic?
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
3,364
Location
Chesapeake, VA
Programming Experience
10+
Which version of C# are you using? Newer versions have nullable type checking enabled by default so you have to explicitly decorate the type to allow nulls.
 

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
1,194
Location
Norway
Programming Experience
10+
When nullable context is enabled you have mark the reference type as nullable by appending ? if it should allow nulls. For example INode?
 

Elad

Member
Joined
Feb 15, 2020
Messages
19
Programming Experience
1-3
Newer versions have nullable type checking enabled by default so you have to explicitly decorate the type to allow nulls.
I'm using the new Visual Studio 2022, so its default is .net Framework 6
But I did not understand what it means to "decorate" Can you give an example that I will understand?
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
3,364
Location
Chesapeake, VA
Programming Experience
10+
See post #3.
 
Top Bottom