generics

Using Java generics in interfaces that return collections. Best practice? Pitfalls?

I ran into some code today that I found questionable. Here's a simplified example (not realistic). public interface IListable { //returns first n items from list public ArrayList getFirstNThings(int n); //returns last n items from list public ArrayList getLastNThings(int n); } Then there's an implementor like so: pu...

Comparing Nested Inner Classes Within Generic Class

I am crafting a nested inner class within a generic class and I'm unsure if I'm writing this properly. Is there anything glaringly wrong here? Here's the code: public class Foo<T> where T : IComparable<T> { protected class Bar : IComparable { private KeyValuePair<T, string> _keyval; public Bar(KeyValuePair<T, s...

Using equals inside a generic class

Hi, I'd like my EqualTester generic class to call the overridden equals(...) method of its generic parameter, but it seems to call Object.equals instead. Here is my test code: import junit.framework.TestCase; public class EqualityInsideGenerics extends TestCase { public static class EqualTester<V> { public boolean check(...

C# Generics - How do I return a specific type?

Maybe I'm going about this all wrong. I have a bunch of classes that derive from the "Model" class, a base class with a bunch of common properties and methods. I want them all to implement a set of functionality: public abstract void Create(); public abstract T Read<T>(Guid ID); //<--Focus on this one public abstract void Update(); p...

Generics in reverse?

Is there a way to do this without using the Type class? I would rather to use generics. abstract class MyAbstract { protected abstract T GetSpecialType(); private void MyPrivateFunction() { someT = GetSpecialType(); } private void DoSomething<T>() { } } class MyConcrete : MyAbstract { protected...

How do I declare the generic type of an instance dynamically in java

I am mocking an interface that doesn't use generics, but does take a Class type as an argument. public Object query(Class c, Filter f) {....} Is there a way in my implementation to use c as the argument for a generic? eg. return new ArrayList<c>(); Obviously I could do a switch if I had a know set of values for c, but that is a ve...

C# Enum.Parse Generics

I have regularly wondered why C# has not yet implemeted a Generic Enum.Parse Lets say I have enum MyEnum { Value1, Value2 } And from an XML file/DB entry I wish to to create an Enum. MyEnum val = (MyEnum)Enum.Parse(typeof(MyEnum), "value1", true); Could it not have been implemented as something like MyEnum cal = Enum.Parse<...

Is it worthwhile to initialize the collection size of a List<T> if it's size reasonably known?

Is it worthwhile to initialize the collection size of a List<T> if it's reasonably known? Edit: Furthering this question, after reading the first answers this question really boils down to what is the default capacity and how is the growth operation performed, does it double the capacity etc.? ...

Using Unity, How do I autoregister a generic class with a generic interface without registering EVERY type to it.

I am using Unity and Unity.AutoRegistration. This line for Unity: unityContainer.RegisterType(typeof(IAction<>), typeof(Action<>)); effectively registers every class in the project to IAction/Action: unityContainer.RegisterType<IAction<ObjectA>, Action<ObjectA>>(); unityContainer.RegisterType<IAction<ObjectB>, Action<ObjectB>>(); uni...

Java generics: Collections.max() signature and Comparator

I understand the get and put principle for collections: if a method takes in a collection that it will write a type T to, the parameter has to be Collection<? super T>, whereas if it will read a type T from, the parameter has to be Collection<? extends T>. But could someone please explain the Collections.max() signature: public static ...

c# exit generic ForEach that use lambda

Does anyone know if it is possible to exit a generic ForEach that uses lambda? e.g. someList.ForEach(sl => { if (sl.ToString() == "foo") break; // continue processing sl here // some processing code } ); This code itself won't compile. I know I could use a regular foreach but for consistency I want to use lamb...

generic was used with wrong number of arguments error?

Does anyone know what on earth this is? i can't get it to go away. •model {"The generic type 'System.Web.Mvc.ViewUserControl`1' was used with the wrong number of generic arguments in assembly 'System.Web.Mvc... it happens when i call a newly constructed model that i pass to a partial view, and try using/calling some methods of it in the...

Why does an instance of a generic class get altered on a separate thread when an instance of an ordinary class does not?

Hi, When an object is altered in a method that runs on a separate thread, the object is not altered on the calling thread (the thread that started the thread on which the method runs). However, if the class that defines the object is generic, the object gets altered on the calling thread. For example: I have two classes: public class...

Is it possible to pass in more than one generically typed parameter to a method?

I currently have this method header: public virtual void SetupGrid<T>() where T : class, new() { } I want to pass in another anonymous class, I guess something like this: public virtual void SetupGrid<T><T2>() where T,T2 : class, new() { } How can I do this? ...

Why doesn't Dictionary<TKey, TValue> have an IEnumerable<KeyValuePair<TKey, TValue>> ctor?

Okay - so I know it's simple to build a factory method that provides the functionality; but given that Dictionary<TKey, TValue> is IEnumerable<KeyValuePair<TKey, TValue>>, shouldn't it have a Ctor equivalent to, for example, List<T>'s ctor(IEnumerable<T> range)? It's even sillier given that it provides a Ctor that takes an IDictionary<T...

Generics and Duck-Typing XML in .NET?

I'm working with some XML representations of data instances. I'm deserializing the objects using .NET serialization but something in my soul is disturbed by having to write classes to represent the XML... Below is what I'd LOVE to do but I don't know if the syntax or if it is even possible: Consider the following: dim xmlObject = Som...

Extending a Scala collection

I want a Map that throws on attempt to overwrite a value for existing key. I tried: trait Unoverwriteable[A, B] extends scala.collection.Map[A, B] { case class KeyAlreadyExistsException(e: String) extends Exception(e) abstract override def + [B1 >: B] (kv: (A, B1)): Unoverwriteable[A, B1] = { if (this contains(kv _1)) t...

Dictionary using generics

Hey guys, I am currently writing a resource manager for my game. This is basically a class that will handle all kinds of other objects of different types, and each object is referred to by name (a System.String). Now this is my current implementation, but since I am using a dictionary of objects I will still need to cast every object. I...

WCF RESTful Services Using Interface with Generics

I have an interface similar to this: [ServiceContract] public interface IBaseService<T> { [OperationContract] [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] List<T> LoadById(string value); [OperationContract] [WebInvoke(Method = "GET", BodyStyle = WebMessage...

Conditional typing in generic method

Consider the following (heavily simplified) code: public T Function<T>() { if (typeof(T) == typeof(string)) { return (T) (object) "hello"; } ... } It's kind of absurd to first cast to object, then to T. But the compiler has no way of knowing that the previous test assured T is of type string. What is the most eleg...