Search code examples
c#nullableconditional-operatorshorthand

Shorthand nullable variable assignment in C#


In my C# WPF project I am trying to assign a value to nullable short with the shorthand function:

short? var = (textbox.Text.Length > 0) ? short.Parse(textbox.Text) : null;

Visualstudio does not allow to have a different type to be assigned (short & null). Is there a solution to keep the shorthand function?

Framework: .Net Framework 4.8.1


Solution

  • The basic issue is that the null type cannot be implicitly converted to short. There are a number of ways to solve this, my preference is to use default.

    short? i = (textbox.Text.Length > 0) ? short.Parse(textbox.Text) : default(short?);