Accessing the value contained within a record struct
I have a
record struct
of AssessmentResponse
:
I understand this is an immutable object, in that once its been created it can't be modified... but how do I get access to the Id of this DTO for use in my code?
obviously the last line doesn't work but I'm not trying to modify the record struct, I just want access to the data.
I'm passing the AssessmentResponse?
if it exists to the Blazor component, and want to access the Id section for the API call to update the record in my database. My AssessmentService.Update
call requires an Guid, AssessmentRequest
I guess alternatively I could modify the AssessmentRequest to have an Id property contained within it and allow it to be nullable? but there's got to be a way to access the Id within the record struct
and assign its value to another variable for use elsewhere.5 Replies
AssessmentResponse?
is syntactic sugar for Nullable<AssessmentResponse>
See here on how to work with nullable value types (structs); specifically, to get the value from a Nullable<AssessmentResponse>
, you would have to go through the .Value
property;i.e.: ParentAssessment.Value.Id
. Do note that you should check if ParentAssessment
is null
before accessing Value
.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-typesNullable value types - C# reference
Learn about C# nullable value types and how to use them
ohhhh, I kept trying to do that but in the wrong order. I was using
ParentAssessment.Id.Value
. Let me give that a try.
I'm catching the null in another spot and shortened it to just show what i was having an issue with
Give me a few and I'll report back
Fantastic, that was it
I'll read up more on that link you sent. Thanks!
Also, that .HasValue feels like it would be a lot cleaner than always doing if (Id is not null)
or some variation of thatYou could also do
if(nullableVariable is {} variable)
; that will extract the underlying value and you can then use it in the body of the if statement: var id = variable.Id;
Is it essentially creating a copy of it?
so
?
At that point, I wouldn't need to make another copy of it to
assessmentId
, I could just use assessment.Id
as I see fit?
yes
but your if condition in your code ends at the semicolon; that wouldn't compile
Ah there might be some confusion, in my previous message "You could also do
if(nullableVariable is {} variable)
", the semicolon was not part of the sample code :)