Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does trying to use string? (Nullable string) in C# produce a syntax error?

I have a method that returns null if the postcode is invalid, and just returns the string if it is valid. It also transforms the data in certain cases.

I have the following unit test below but I am getting syntax errors on the lines where it is using string?. Could anyone tell me why?

    public void IsValidUkPostcodeTest_ValidPostcode()
    {
        MockSyntaxValidator target = new MockSyntaxValidator("", 0);
        string fieldValue = "BB1 1BB";
        string fieldName = "";
        int lineNumber = 0;
        string? expected = "BB1 1BB"; 
        string? actual;

        actual = target.IsValidUkPostcode(fieldValue, fieldName, lineNumber);

        Assert.AreEqual(expected, actual);
    }
like image 635
ediblecode Avatar asked Dec 20 '11 15:12

ediblecode


Video Answer


2 Answers

The ? suffix on the name of a type is an alias for using Nullable<T> (section 4.1.10 of the C# 4 spec). The type parameter for Nullable<T> has the struct constraint:

public struct Nullable<T> where T : struct

This constrains T to be a non-nullable value type. That prohibits you from using string, as System.String is a reference type.

Fortunately, as string is a reference type, you don't need to use Nullable<T> - it already has a null value (the null reference):

string x = null; // No problems here
like image 60
Jon Skeet Avatar answered Oct 27 '22 01:10

Jon Skeet


string is already a nullable type an doesn't need a ?

like image 20
ShaneBlake Avatar answered Oct 27 '22 02:10

ShaneBlake