frosty
frosty

Reputation: 5370

how to cast object to get Id in C#

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?

Phase 2 ## using an interface

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

Answers (1)

Tim Robinson
Tim Robinson

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

Related Questions