Malte
Malte

Reputation: 3

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

Upvotes: 0

Views: 77

Answers (1)

Derrick Moeller
Derrick Moeller

Reputation: 4950

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?);

Upvotes: 0

Related Questions