Sep 26, 2008

Method Hiding... Polymorphism in C#

In the following code:

interface IBand
{
int ID {get;set;}
string Name {get;set;}
void GetStatus();
}
public class Band : IBand
{
public int ID { get; set; }
public string Name { get; set; }

public Band()
{
GetStatus();
}
public void GetStatus()
{
ID = 555;
Name = "Ring";
Console.WriteLine("Base Class Called");
}
}

public class ABand : Band, IBand
{
public string Update { get; set; }

public ABand() : base() {}

public new void GetStatus()
{
ID = 655;
Name = "TEsst";
Update = "ddd";
Console.WriteLine("Derived class Called");
}
}
class Program
{
static void Main(string[] args)
{
IBand band = new ABand();
band.GetStatus();
}

}

We have 2 classes, Band and ABand which implement the IBand interface explicitly.

Now the call to band.GetStatus in Main will display "Derived class called". This will only happen if the Derived class (ABand) also implements the interface IBand explicitly (not in the literal sense in that it does not implement the methods using the IBand.GetStatus syntax)

If the ABand class does not implement the IBand interface explicitly (but implicitly since it inherits from Band which implements IBand) then the above code will output "Base class called"

However note one thing, that when the CTor for ABand is invoked it will invoke the ctor Band class and which will call GetStatus() method from within Band class hence this will output "Base class called" even though the ABand class has implemented the IBand interface explicilty.

kick it on DotNetKicks.com

Sep 9, 2008

Linq To XML : Check for existence of an element

var bookQuery = 
from book in bookXml.Descendants("Item")

let attributes = book.Element("ItemAttributes")

let price = Decimal.Parse((
book.Elements("OfferSummary").Any()
&& book.Element("OfferSummary").Elements("LowestNewPrice").Any()
? book.Element("OfferSummary").Element("LowestNewPrice").Element("Amount").Value
: (attributes.Elements("ListPrice").Any()
? attributes.Element("ListPrice").Element("Amount").Value
: "0"))) / 100

select new {Price = price};


The trick is to use the Elements(“node”) instead of Element(“node”) and then use the Any() function which will return true if an element of that name exists.

Some other LINQ tips:

Some of the extensions that one can use are Intersect,Union && Except
var list1 = new List<int> { 2, 4, 9, 11, 3, 6 };
var list2 = new List<int> { 3, 8, 4, 30, 9, 16 };
var newlist = list1.Intersect(list2);

This returns : 3,4,9
newlist = list1.Union(list2);
this returns : 2,3,4,6,8,9,11,16,30. finally
newlist = list1.Except(list2);
returns : 2,11,6

kick it on DotNetKicks.com