Reputation: 32808
I have the following in my model:
public string Subject {
get {
return SubjectReference.GetSubject(SubjectID);
}
}
How can I make this so that if the SubjectID is null then the get call will return null? I think there's a way to do this with the ? operator but can I use this inside of a class for model properties?
Upvotes: 0
Views: 67
Reputation: 8359
You may try this
public string Subject {
get {
return SubjectID==null ? null : SubjectReference.GetSubject(SubjectID);
}
}
Upvotes: 1
Reputation: 26502
You may use either a regular if
statement, or the ternary operator (?
operator) as you've mentioned. Examples of each are provided below.
Using an if statement:
public string Subject {
get {
if (SubjectID == null) {
return null;
}
return SubjectReference.GetSubject(SubjectID);
}
}
Using ternary operator:
public string Subject {
get {
return SubjectID == null ? null : SubjectReference.GetSubject(SubjectID);
}
}
Upvotes: 3
Reputation: 19020
How about
public string Subject
{
get
{
return SubjectID == null ? null : SubjectReference.GetSubject(SubjectID);
}
}
You could consider string.IsNullOrEmpty(SubjectID)
instead when an empty string for SubjectID
should also result in a null
return.
If your property is a reference type then of course null
is a legal return value.
Upvotes: 4