Category: generics

C# LINQ to SQL: Refactoring this Generic GetByID method

I wrote the following method. public T GetByID(int id) { var dbcontext = DB; var table = dbcontext.GetTable<T>(); return table.ToList().SingleOrDefault(e => Convert.ToInt16(e.GetType().GetProperties().First().GetValue(e, null)) == id); } Basically it’s a method in a Generic class where T is a class in a DataContext. The method gets the table from the type of T (GetTable) and checks […]

Confused by Java generics requiring a cast

I’m confused by the following code: import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class GenericsTest<T extends List> { public void foo() { T var = (T) new LinkedList(); } public static void main(String[] args) { GenericsTest<ArrayList> gt1 = new GenericsTest<ArrayList>();; System.out.println(“Done”); } } The runtime type of T appears to be java.util.List, regardless of […]