Home > Software engineering >  Why can I not convert Foo<T?> to Foo<T>
Why can I not convert Foo<T?> to Foo<T>

Time:09-08

I have a generic Struct "FileProperty" which consists of an int 'offset' and a T 'value'. If I do something like the following..:

FileProperty<long?> fp1 = new FileProperty(value: null, offset: 0);
fp1.value = 1;

..neither of the following work:

FileProperty<long> fp2;
fp2 = fp1;                       // Cannot implicitly convert type 'Database.FileProperty<long>' to 'Database.FileProperty<long?>'
fp2 = (FileProperty<long>) fp1;  // Cannot convert type 'Database.FileProperty<long>' to 'Database.FileProperty<long?>'

Even if I write an explicit conversion I just get:
'User-defined operator cannot convert a type to itself'
which makes sense but doesn't help me.

The issue I am having is that I know 'T? != null' but I can't convert Foo<T?> to Foo.

CodePudding user response:

Its due the difference between Foo<Nullable<T>> and Foo<T>. These are very different types, and in the name of strict typing a cast is blocked because it needs to know that the nullability will be dealt with upfront

One way to properly handle this cast is to use the null coalescing operator to check if its null, and if so provide the fallback value for it

In this snippet I chose to use the default operator. Since FileProperty is a struct, it will default to a struct where value is null and offset is 0. If this is undesirable, swap it out to fit your needs

FileProperty<long?> fp1 = new FileProperty(value: 1, offset: 0);

FileProperty<long> fp2 = fp1 ?? default(FileProperty<long>);

You may also just want to throw an exception if its null

FileProperty<long> fp2;
if (fp1 != null) fp2 = fp1;
else throw new Exception("No");
  • Related