Giving a string a null value

2.7k views Asked by At

I am in need of some information on how I can set this string in the code snippet below to a null value.

[Index(IsUnique = true)]
[StringLength(450)]
public string StockCode
{
    get { return _stockCode; }
    set { _stockCode = value.ToUpper(); } //(ToUpper)<<-- Error
}

When I try to do it the normal way public string? StockCode I get the error at my .ToUpper and it says:

'System.Nullable' does not contain a definition for 'ToUpper' and no extension method 'ToUpper' accepting a first argument of type 'System.Nullable' could be found (are you missing a using directive or an assembly reference?)

I am no expert or pro C# coder, so I have no clue how to set my string to a null value and still use .ToUpper in the way I am trying to do it. :( Any advice would be appreciated!

2

There are 2 answers

2
Steve On BEST ANSWER

Not sure if you want to face all the complications when you will try to get this property but simply adding a check for the null value before applying ToUpper()

set { _stockCode = (value == null ? null : value.ToUpper()); }
1
VidasV On

You cannot use nullable type on string. String by default accepts null values and can be checked by string.IsNullOrEmpty(StockCode);