Type Safety


In the previous example we used generic types for our query, constraining on only one type of objects. However LINQ is flexible enough to allow querying across types:

LinqExample.cs: SelectEverythingByName
01private static void SelectEverythingByName() 02 { 03 IObjectContainer container = Database(); 04 if (container != null) 05 { 06 try 07 { 08 var result = from object o in container 09 where o.ToString().StartsWith("Test") 10 select o; 11 IList objects = result.ToList(); 12 ListResult(objects); 13 } 14 catch (Exception ex) 15 { 16 System.Console.WriteLine("System Exception: " + ex.Message); 17 } 18 finally 19 { 20 CloseDatabase(); 21 } 22 } 23 }
LinqExample.vb: SelectEverythingByName
01Private Shared Sub SelectEverythingByName() 02 Dim container As IObjectContainer = Database() 03 If container IsNot Nothing Then 04 Try 05 06 Dim result = From o In container Where (o.ToString().StartsWith("Test")) Select o 07 Dim objects As IList = result.ToList() 08 ListResult(objects) 09 Finally 10 CloseDatabase() 11 End Try 12 End If 13 End Sub

We have both Car and Pilot objects that can correspond the selected criteria and - yes, we will get a mixed list of both. This feature is potentially dangerous as in the development cycle you may lose control of the objects that answer the criteria and get unexpected results. Be aware and use untyped LINQ queries with caution.