Reputation: 5370
I'm using nhibernate and have an issue when some of objects are null. ie
Region is null and i get a null ref when i go userProfile.Region.Id
Of course throughout my app i could do something like
var regionId = (Model.UserProfile.Region != null) ? Model.UserProfile.Region.Id : 0);
But i think ideally i would like null objects ids to equal 0.
Is this achievable? Is this desirable?
i now have:
interface IEntity
{
int GetIdOrZero();
}
and
public class Region :IEntity
{
public virtual int Id { get; set; }
public int GetIdOrZero()
{
return (this != null) this.Id : 0;
}
}
what is the best way to test if region is null?
Upvotes: 1
Views: 289
Reputation: 54734
You can't change the behaviour of a null reference, but you could define an extension method that does what you want:
public static class RegionExtensions
{
public static int GetIdOrZero(this Region region)
{
return region == null ? 0 : region.Id;
}
}
Edit:
public interface IEntity
{
int Id { get; }
}
public class Region : IEntity { ... }
public static class EntityExtensions
{
public static int GetIdOrZero(this IEntity entity)
{
return entity == null ? 0 : entity.Id;
}
}
Upvotes: 3