Hi
Ive seen it time and time again whereby an instance property member of a class is accessed followed by an instance method, all of the same line.
For example given this source code:-
var doc = XDocument.Load("aUrlReferencingaXMLDoc");
foreach(var item in doc.Root.Elements())
What I would like to know is how is this possible to access the Elements method straight from the Root property? is is because they both have the same Return type, in this case XElement?
Regards
Steven
Loading
VulpesPosted Jul 12, 2012, 11:50 AM
If a property returns an object of a certain type and that object has a method (or inherits a method from its base class) which you want to call, then you can chain the two operations together as in the above line.
In fact you can continue with this chaining (unless it's a void method) but, if you carry this too far, then the point will be reached where the code becomes difficult to read and, hence, maintain.
Guest UserPosted Jul 12, 2012, 11:55 AM
Guest UserPosted Jul 12, 2012, 11:41 AM
In general, being able to access various instance members using the notation property then method as like the example below:-
doc.Root.Elements();
Depends on the Return type of the object and also class inheritance ie Root could be of type XElement and Elements say for arguement sake could be of type XNode? being able to use the 2 side by side is due to the fact XNode inherits from XElement?
Regards
Steven
VulpesPosted Jul 12, 2012, 11:24 AM
Guest UserPosted Jul 12, 2012, 10:59 AM