The MS Docs explanation about null-coalescing operator (note emphasized part):
A nullable type can represent a value from the type’s domain, or the
value can be undefined (in which case the value is null). You can use
the ?? operator’s syntactic expressiveness to return an appropriate
value (the right hand operand) when the left operand has a nullible
type whose value is null. If you try to assign a nullable value type
to a non-nullable value type without using the ?? operator, you will
generate a compile-time error. If you use a cast, and the nullable
value type is currently undefined, an InvalidOperationException
exception will be thrown.
Since the right-hand operand must return appropriate value of corresponding data type, it can't be set directly as null even the assigned variable has nullable data type (both operands must be have same data type).
Basically when you define a null-coalescing operator as this:
Portrait_PrimaryImage = _SiteImagesModel_ImagesViewModel.PrimaryImage ?? [DefaultValueIfNull];
It will translated as this:
Portrait_PrimaryImage = _SiteImagesModel_ImagesViewModel.PrimaryImage == null ? [DefaultValueIfNull] : _SiteImagesModel_ImagesViewModel.PrimaryImage;
Since both operands in ternary operator & null-coalescing operator must have same type, if you still want null value to be passed, you can cast the right-hand operand to proper type like this:
Portrait_PrimaryImage = _SiteImagesModel_ImagesViewModel.PrimaryImage ?? (bool?)null;
Portrait_RecordID = _SiteImagesModel_ImagesViewModel.RecordID ?? (Guid?)null;
Portrait_RelatedImage = _SiteImagesModel_ImagesViewModel.RelatedImage ?? (bool?)null;
Note that null
is not at the same type as Nullable<bool>
, you need to cast into bool?
to get same data type.
As in your case, ternary operator usage just enough, no need to use null-coalescing operator when the second operand is null
:
Portrait_Enabled = _SiteImagesModel_ImagesViewModel == null ? null : (bool?)_SiteImagesModel_ImagesViewModel.Enabled;
Portrait_RecordID = _SiteImagesModel_ImagesViewModel == null ? null : (Guid?)_SiteImagesModel_ImagesViewModel.RecordID;
Portrait_RelatedImage = _SiteImagesModel_ImagesViewModel == null ? null : (bool?)_SiteImagesModel_ImagesViewModel.RelatedImage;
References:
Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and <null>
How to set null to a GUID property