Search code examples
c#nhibernatereflectionfluent-nhibernateicollection

How to check if a state object is of type ICollection


I use the nhibernate interceptor to compare values of the old state and the current state of the entity properties but some of the properties are of type ICollection so could anyone guide me about how to check if an object is of type ICollection

this is my code

    public void OnPostUpdate(NHibernate.Event.PostUpdateEvent @event)
    {
        var entityToAudit = @event.Entity as IAuditable;
        string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AuditLog.txt");
        using (StreamWriter sw = File.AppendText(path))
        {
            for (int i = 0; i < @event.OldState.Length; i++)
            {
                string propertyName = @event.Persister.PropertyNames[i];
                if (@event.OldState[i] != null)
                {
                    if (!@event.OldState[i].Equals(@event.State[i]))
                    {
                        sw.WriteLine("the value of "+ propertyName + " has been changed from " + @event.OldState[i] + " to " + @event.State[i]);
                    }
                }
                else
                {
                    if (@event.State[i] != null)
                    {
                        sw.WriteLine("the value of "+ propertyName + " has been changed from being empty to " + @event.State[i]);
                    }
                }
            }
        }
    }

Solution

  • You have more than one options to do this, use is or use as with null checking:

    if (obj is ICollection){
        //your logic
    }
    

    Or, if you need the object as ICollection later on, I recommend to use as:

    var icoll = obj as ICollection
    if (icoll != null){
        //use icoll
        //icoll.Something();
    }