Good morning.
Let me show you some code:
//Db is a database of Tag objects, sort of
Db db;
string code = "123";
var selectedTag = db.Select(new Predicate<Tag>(tag => tag.Code == code));
//...
class Db
{
//A query method, accepting a Predicate
public Tag Select(Predicate<Tag> predicate)
{
/* Here, using Intellisense, I see that Target property is a Tag object,
but I can't cast it to Tag! Why??
*/
var t = predicate.Target as Tag; //Always null!
}
}
I basically have a simple database of Tag object; when a caller invoke Select method, I would retirieve Tag object istance from predicate, but actually I can’t get it work.
Using Intellisens in debug, when I am in Select method I clearly see that predicate.Target is referenced to my Tag object, but I don’t know how to retrieve it.
Any ideas?
Thank you.
EDIT
If I try to unsafely cast predicate.Target to Tag, this way:
var t = (Tag)predicate.Target;
I get an InvalidCastException; ok, but Exception message says I cannot cast object of type DbTests to type Tag.
DbTests is the NUnit test class I’m using for my testing purpose (obviuosly…:).
Weird!
EDIT 2
Typo in line:
var selectedTag = db.Select(new Predicate<Tag>(tag => tag.Code == code));
Your
Selectmethod takes a delegate (the type of that delegate is aPredicate<T>, more specificallyPredicate<Tag>). that delegate points to an instance and a method. What you’ve passed in for the delegate is a lambdatag => tag.Code == code. That lambda causes the compiler to generate a method for this code. That method is either contained on the instance that callsSelect, or in a new class. If the generated method isstatic, there will be no instance andTargetwill benull. In any case that class that contains that method is notTag(unless the call toSelectis within theTagclass; but you didn’t detail that). So,Targetcannot be aTagobject and can never be cast toTagsuccessfully.The predicate that select receives should be given a
Tagobject. For example:it’s not clear what you really want to do within
Select; butPredicate<Tag>just returnstrueorfalsedepending on theTaggiven to it.Update:
In your example, it’s as if you wrote this:
There is no
Taginstance anywhere in the above snippet.Update:
If you used an instance method from the containing class, for example:
Then the predicate sent to select will have an instance associated with it and thus
Targetwill not be null. In the above code,Targetwould be of typeDbTestBut, if you put the call to Select withinTagData(e.g.DbTestswas renamed toTagData) thenTargetwould be of typeTagDataand show you instance members fromTagDataand you’d get what you see in your screen capture.Selectdoesn’t seem like the right term for a method that uses aPredicate<T>