Resumé

Using the Predicates in .Net 2.0

Cristian Merighi () 0.00

This article brings a couple of examples about how to use (even parametric) predicate delegates and show the way to write more elegant code for your custom generic collections.
This article is obsolete. Some functionalities might not work anymore. Comments are disabled.

One of the features that firstly made me fall in love with the 2.0 version of the Framework was undoubtably the strong-typing of the lists, the so named Generics.

The power and usefulness shines to the eyes even of a newbie developer.
Besides, snooping deeper into the members of the various classes, we can find surely worthy gems, maybe not because of performance but certainly for elegance and code purity reasons.

That's what Predicates are about.

A couple of examples about how to use this predicate delegates - both "static" and parametric - with a custom collection are following:
(I omit the theory which is better retrieved from the official reference)

Business Logic Class "Period":

public class Period{
    
    public Period(int id, DateTime from, DateTime to)
    {
        _ID = id;
        _From = from;
        _To = to;
    }
    
    private int _ID = 0;    
    public int ID
    {
        get{ return _ID; }
    }
    
    private DateTime _From = DateTime.MinValue;    
    public DateTime From
    {
        get{ return _From; }
    }
    
    private DateTime _To = DateTime.MinValue;    
    public DateTime To
    {
        get{ return _To; }
    }  

}

Custom collection enriched by methods which exploit predicate delegates:

public class PeriodCollection : System.Collections.Generic.List<Period>{

    public PeriodCollection() : base(){}
    
    // Custom methods
    
    // Use scope parameter to use the predicate in a "dynamic" way
    private int scopeID = 0;
    public Period FindByID(int itemID)
    {
        scopeID = itemID;
        return this.Find(MatchesID);
    }
    
    public System.Collections.Generic.List<Period> GetAllCurrent(){
        return this.FindAll(MatchesNow);
    }
    
    
    // Predicates
    private bool MatchesID(Period item)
    {
        return scopeID == item.ID;
    }
    
    private bool MatchesNow(Period item)
    {
        return item.From < DateTime.Now && item.To > DateTime.Now;
    }

}

I confirm the concept: predicates don't give benfits at the performance level, they avoid hard-coded loops and confer much more elegance to the code.

Take care. Bye.

Feedbacks

  • Re: Using the Predicates in .Net 2.0

    musclebai Thursday, June 14, 2007 0.00

    gr8 help thanx

feedback
 

Syndicate

Author

Cristian Merighi facebook twitter google+ youtube

Latest articles

Top rated

Archive

Where am I?

Author

Cristian Merighi facebook twitter google+ youtube

I'm now reading

Feeds