DEV Community

loading...
Cover image for A great feature in C# 9.0 (Simplified Parameter Null Validation)

A great feature in C# 9.0 (Simplified Parameter Null Validation)

lleonardogr profile image Leonardo Gasparini Romão Updated on ・1 min read

Well, as C# advances, some features are been more simplified inside the language. One common problem that beginners programmers have is how to deal with nullable variables.

In the first versions of C# language, validate null values were very explicity when I was coding, eg...

public static void Main()
    {
        string Name = null;
        if(Name == null)
            throw new NullReferenceException
            ("Error, the name is null");
    }
Enter fullscreen mode Exit fullscreen mode

After version 4.0 of .Net Framework, C# has gain some other interesting options to use. eg...


public static void Main()
    {
        //Using ?? Operator
        string Name = null ?? "Undefined";
        Console.WriteLine(Name);

        Name = null;

        //Using String Extension Mehtods
        if(String.IsNullOrEmpty(Name))
            throw new NullReferenceException
            ("Error, the name is null or Empty");

    }

Enter fullscreen mode Exit fullscreen mode

But now with C# 9.0, I can simplify all of this with the !! Operator like:


public static void Main()
    {
        string Name = null;
        ManipulateString(Name);
        OtherManipulateString(Name)
    }

    //Using new ! Operator to throw exception
    public static string ManipulateString(string s!)
    {
        return s + " is a Valid string";
    }

    //Using new !! Operator to substitute null to other things like "" (probably)
    public static string OtherManipulateString(string s!!)
    {
        return s + " is a Valid string";
    }

Enter fullscreen mode Exit fullscreen mode

although it is too early to validate whether it will be interesting to use this operator, in fact, it seems an interesting option to consider, despite not making it so explicit in the code, the economy of lines of code may be surprising.

Useful links:
http://www.macoratti.net/20/02/c_versao9.htm
https://www.infoq.com/news/2020/06/CSharp-9-Null/
https://www.c-sharpcorner.com/article/null-value-and-null-reference-handling-c-sharp6-to-c-sharp-9-new-features-day-1/

Discussion (2)

pic
Editor guide
Collapse
shaijut profile image
Shaiju T • Edited

Nice 😄 , But I think its not readable. == null is better than s!

Collapse
lleonardogr profile image
Leonardo Gasparini Romão Author

Yeah, I think that == suits better for conditionals or for Object construction I guess, but to organize methods reducing the number of lines of code, plus the validation implicit makes Method(string s!) better than Method(string? s)...//string validation

But I'm certainly need test this more clearly 😄