1

I was under the impression that if I pass a class to a function as a reference, that reference can be nullable.

Example: I have a code-first entity class / database table:

public class Table1
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int FillID { get; set; }
    public int OrderID { get; set; }
    public int FillQuantity { get; set; }
    public DateTime TransactionDateTime { get; set; }
    public virtual tblInstruments tblInstruments { get; set; }
 }

I'd like to create a function which has the following signature:

public static void Function1 (int? i, Table1? t)

The Table1? t gives the a error:

only non-nullable value type could be underlying of System.Nullable

So I'm not sure what I'm doing wrong. I tried

public static void Function1 (int? i, ref Table1? t)

But that did not resolve the issue.

Any pointers would be greatly appreciated.

Ed Landau
  • 966
  • 2
  • 11
  • 24
  • 1
    All reference variabls are by default nullable. They can take a null value. It is primitive and structs wich are not nullable by default. – Christopher Sep 21 '19 at 23:38
  • Here's an article by Jon Skeet discussing value types, reference types, and passing by value or reference. https://jonskeet.uk/csharp/references.html After reading that take a look at the code for [`Nullable`](https://referencesource.microsoft.com/#mscorlib/system/nullable.cs) which is what the `T?` is short for – juharr Sep 21 '19 at 23:59

1 Answers1

4

All reference types are nullable by default, you don't need to add the ? modifier. From the docs:

The underlying type T can be any non-nullable value type. T cannot be a reference type.

So your code should be:

public static void Function1 (int? i, Table1 t)

The next version of C#, version 8 will introduce nullable reference types, you will need to enable to option on a per-project basis, but that will allow you to have non-nullable reference types.

DavidG
  • 113,891
  • 12
  • 217
  • 223