Search Results

Search found 1008 results on 41 pages for 'generics'.

Page 13/41 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >

  • Collect all extension methods to generic class in another generic class

    - by Hun1Ahpu
    I'd like to create a lot of extension methods for some generic class, e.g. for public class SimpleLinkedList<T> where T:IComparable And I've started creating methods like this: public static class LinkedListExtensions { public static T[] ToArray<T>(this SimpleLinkedList<T> simpleLinkedList) where T:IComparable { //// code } } But when I tried to make LinkedListExtensions class generic like this: public static class LinkedListExtensions<T> where T:IComparable { public static T[] ToArray(this SimpleLinkedList<T> simpleLinkedList) { ////code } } I get "Extension methods can only be declared in non-generic, non-nested static class". And I'm trying to guess where this restriction came from and have no ideas.

    Read the article

  • Reflective Generic Detection

    - by Aren B
    Trying to find out if a provided Type is of a given generic type (with any generic types inside) Let me Explain: bool IsOfGenericType(Type baseType, Type sampleType) { /// ... } Such that: IsOfGenericType(typeof(Dictionary<,>), typeof(Dictionary<string, int>)); // True IsOfGenericType(typeof(IDictionary<,>), typeof(Dictionary<string, int>)); // True IsOfGenericType(typeof(IList<>), typeof(Dictionary<string,int>)); // False However, I played with some reflection in the intermediate window, here were my results: typeof(Dictionary<,>) is typeof(Dictionary<string,int>) Type expected typeof(Dictionary<string,int>) is typeof(Dictionary<string,int>) Type expected typeof(Dictionary<string,int>).IsAssignableFrom(typeof(Dictionary<,>)) false typeof(Dictionary<string,int>).IsSubclassOf(typeof(Dictionary<,>)) false typeof(Dictionary<string,int>).IsInstanceOfType(typeof(Dictionary<,>)) false typeof(Dictionary<,>).IsInstanceOfType(typeof(Dictionary<string,int>)) false typeof(Dictionary<,>).IsAssignableFrom(typeof(Dictionary<string,int>)) false typeof(Dictionary<,>).IsSubclassOf(typeof(Dictionary<string,int>)) false typeof(Dictionary<,>) is typeof(Dictionary<string,int>) Type expected typeof(Dictionary<string,int>) is typeof(Dictionary<string,int>) Type expected typeof(Dictionary<string,int>).IsAssignableFrom(typeof(Dictionary<,>)) false typeof(Dictionary<string,int>).IsSubclassOf(typeof(Dictionary<,>)) false typeof(Dictionary<string,int>).IsInstanceOfType(typeof(Dictionary<,>)) false typeof(Dictionary<,>).IsInstanceOfType(typeof(Dictionary<string,int>)) false typeof(Dictionary<,>).IsAssignableFrom(typeof(Dictionary<string,int>)) false typeof(Dictionary<,>).IsSubclassOf(typeof(Dictionary<string,int>)) false So now I'm at a loss because when you look at the base.Name on typeof(Dictionary) you get Dictionary`2 Which is the same as typeof(Dictionary<,>).Name

    Read the article

  • C# - Cast object to IList<T> based on Type

    - by blu
    I am trying out a little reflection and have a question on how the cast the result object to an IList. Here is the reflection: private void LoadBars(Type barType) { // foo has a method that returns bars Type foo = typeof(Foo); MethodInfo method = foo.GetMethod("GetBars") .MakeGenericMethod(bar); object obj = method.Invoke(foo, new object[] { /* arguments here */ }); // how can we cast obj to an IList<Type> - barType } How can we cast the result of method.Invoke to an IList of Type from the barType argument?

    Read the article

  • How to create generic class which takes 3 types.

    - by scope-creep
    I'm trying to make a generic class that takes 3 types, either a simple string, IList or a IList. public class OntologyStore { } public sealed class jim<T> where T:new() { IList<string> X = null; IList<OntologyStore> X1 = null; public bob() { if (typeof(T) == typeof(String)) { X = new List<string>(); } if (typeof(T) == typeof(OntologyStore)) { X1 = new List<OntologyStore>(); } } } I can easily create, which you would expect to work, jim<OntologyStore> x1=new jim<jim<OntologyStore>() as you would expect, but when I put in jim<string> x2=new jim<string>() the compiler reports the string is non abtract type, which you would expect. Is it possible to create a generic class, which can instantiate as a class which holds string, or a IList or an IList?

    Read the article

  • Structuremap and generic types

    - by James D
    Hi I have a situation which seems a bit different from others I've seen. For clarrification, this isn't the normal question eg; something like IAClass maps to AClass etc - that involves using basically a single concrete classes per interface. This involves having a single generic class, but I want to be able to load ALL possible usages of it. Eg - the main class is of public class MyClass<TDomainObject> : IMyClass<TDomainObject> where TDomainObject : DomainObject So example usages would be IMyClass<Person> p = new MyClass<Person>; IMyClass<Employer> p = new MyClass<Employer>; I.e. for all DomainObjects I would like to be able to load a MyClass< for. So you can see I don't use a specific class for each declaration, they all use the same one. How would I get this loaded into StructureMap?

    Read the article

  • Generic wrapper for System.Web.Caching.Cache functions

    - by David Neale
    I've created a generic wrapper for using the Cache object: public class Cache<T> where T : class { public Cache Cache {get;set;} public CachedKeys Key {get;set;} public Cache(Cache cache, CachedKeys key){ Cache = cache; Key = key; } public void AddToCache(T obj){ Cache.Add(Key.ToString(), obj, null, DateTime.Now.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); } public bool TryGetFromCache(out T cachedData) { cachedData = Cache[Key.ToString()] as T; return cachedData != null; } public void RemoveFromCache() { Cache.Remove(Key.ToString()); } } The CachedKeys enumeration is just a list of keys that can be used to cache data. The trouble is, to call it is quite convuluted: var cache = new Cache<MyObject>(Page.Cache, CachedKeys.MyKey); MyObject myObject = null; if(!cache.TryGetFromCache(out myObject)){ //get data... cache.AddToCache(data); //add to cache return data; } return myObject; I only store one instance of each of my objects in the cache. Therefore, is there any way that I can create an extension method that accepts the type of object to Cache and uses (via Reflection) its Name as the cache key? public static Cache<T> GetCache(this Cache cache, Type cacheType){ Cache<cacheType> Cache = new Cache<cacheType>(cache, cacheType.Name); } Of course, there's two errors here: Extension methods must be defined in a non-generic static class The type or namespace name 'cacheType' could not be found This is clearly not the right approach but I thought I'd show my working. Could somebody guide me in the right direction?

    Read the article

  • How do you cast a LinqToSql Table<TEntity> as a Table<IEntity> where TEntity : IEntity?

    - by DanM
    I'm trying to use DbLinq with a SQLite database, but I'm running into a problem when I try to cast an ITable as a Queryable<TEntity>. There is a known bug in DbLinq (Issue 211), which might be the source of my problem, but I wanted to make sure my code is sound and, if it is, find out if there might be something I can do to work around the bug. Here is the generic repository method that attempts to do the cast: public IQueryable<TEntity> GetAll() { return Table.Cast<TEntity>(); // Table is an ITable } This compiles, but if I pass in the interface IPerson for TEntity and the type of the entities in the table is Person (where Person : IPerson), I'm getting this error from DbLinq: S0133: Implement QueryMethod Queryable.Cast. Why am I trying to do this? I have a library project that doesn't know the type of the entity until runtime, but it does know the interface for the entity. So, I'm trying to cast to the interface type so that my library project can consume the data. Questions: Am I attempting an impossible cast or is this definitely a bug in DbLinq? How else could I go about solving my problem?

    Read the article

  • Marshal generic return types for com interop

    - by Israel Chen
    Is it possible to Marshal a generic return type as non-generic for COM interop? Let's say I have the following class: [ComVisible(true)] public class Foo { public IEnumerable GetStr() // Generic return type { yield break; } } I know that IEnumerable implements IEnumerable. Can I force tlbexp.exe (via return: attribute or some other way) to expose GetStr() method as a method returning IEnumerbale?

    Read the article

  • java casting a list

    - by dcp
    Let's say I had: protected void performLogic(List<Object> docs) { ... } In the code where I'm going to be calling this method, I have a List<String> list. I want to call performLogic, passing this list. But it won't work because the lists are 2 different types: public void execute() { List<String> docs = new ArrayList<String>(); performLogin(docs); // won't work } I tried casting to List<Object> also, but that won't work either. So is the only way to do this is to make a new ArrayList of Object and just add the values and then pass it? Just seems cumbersome. I wondered if there was a better way to do it. Thanks.

    Read the article

  • No generic implementation of OrderedDictionary?

    - by AdaTheDev
    I'm using .NET 3.5. I think I know the answer to this, but am looking for confirmation so should be a quick one! There doesn't appear to be a generic implementation of OrderedDictionary (which is in System.Collections.Specialized namespace). Is there one that I'm missing? I've found implementations out there to provide the functionality, but wondered if/why there isn't a generic implementation out-of-the-box and if anyone knows whether it's something in .NET 4.0?

    Read the article

  • Force an unchecked call

    - by François Cassistat
    Hello, Sometimes, when using Java reflection or some special storing operation into Object, you end up with unchecked warnings. I got used to it and when I can't do anything about it, I document why one call is unchecked and why it should be considered as safe. But, for the first time, I've got an error about a unchecked call. This function : public <K,V extends SomeClass & SomeOtherClass<K>> void doSomethingWithSomeMap (Map<K,V> map, V data); I thought that calling it this way : Map someMap = ...; SomeClass someData = ...; doSomethingWithSomeMap(someMap, someData); would give me an unchecked call warning. Jikes does a warning, but javac gives me an error : Error: doSomethingWithSomeMap(java.util.Map,V) in SomeClass cannot be applied to (java.util.Map,SomeClass) Any way to force it to compile with a warning? Thanks.

    Read the article

  • How to check if a generic type definition inherits from another generic type definition

    - by Anne
    I'm trying to check whether an open generic type definition implements some open generic interface. Look at the sample below: public interface IService<T> { } public class ServiceImpl<T> : IService<T> { } private static bool OpenGenericTypeImplementsOpenGenericInterface( Type derivedType, Type interfaceType) { return derivedType.GetInterfaces().Contains(interfaceType); } [TestMethod] public void Verify() { Type openGenericImplementation = typeof(ServiceImpl<>); Type expectedInterfaceType = typeof(IService<>); bool implDoesImplementInterface = OpenGenericTypeImplementsOpenGenericInterface( openGenericImplementation, expectedInterfaceType); // This assert fails. Why? Assert.IsTrue(implDoesImplementInterface); } I found out that the returned type from the Type.GetInterfaces() method does not match the type returned from typeof(IService<>). I can't figure out why that is and how to correctly validate whether some generic type definition inherits or implements some other generic type definition. What's going on here and how do I solve fix this problem?

    Read the article

  • Calling generic method in spring.net application context

    - by Bert Vandamme
    Hi, I'm trying to invoke this method in spring.net, but i'm having trouble getting the configuration right. Method: public void AddRepository(IRepository repository) where TEntity : IEntity { Repositories.Add(repository.GetType().Name, repository); } Config: <object type="Spring.Objects.Factory.Config.MethodInvokingFactoryObject, Spring.Core"> <property name="TargetObject"> <ref local="RepositoryFactory" /> </property> <property name="TargetMethod" value="AddRepository"/> <property name="Arguments"> <list> <ref object="BinaryAssetFileRepository"/> </list> </property> </object>" Is it possible to address generic methods in this way? Thx, Bert

    Read the article

  • Compile error on inheritance of generic inner class extending with bounds

    - by Arne Burmeister
    I have a problem when compiling a generic class with an inner class. The class extends a generic class, the inner class also. Here the interface implemented: public interface IndexIterator<Element> extends Iterator<Element> { ... } The generic super class: public abstract class CompoundCollection<Element, Part extends Collection<Element>> implements Collection<Element> { ... protected class CompoundIterator<Iter extends Iterator<Element>> extends ImmutableIterator<Element> { ... } } The generic subclass with the compiler error: public class CompoundList<Element> extends CompoundCollection<Element, List<Element>> implements List<Element> { ... private class CompoundIndexIterator extends CompoundIterator<IndexIterator<Element>> implements IndexIterator<Element> { ... } } The error is: type parameter diergo.collect.IndexIterator<Element> is not within its bound extends CompoundIterator<IndexIterator<Element>> ^ What is wrong? The code compiles with eclipse, but bot with java 5 compiler (I use ant with java 5 on a mac and eclipse 3.5). No, I cannot convert it to a static inner class.

    Read the article

  • How do you marshall a parameterized type with JAX-WS / JAXB?

    - by LES2
    Consider the following classes (please assume public getter and setter methods for the private fields). // contains a bunch of properties public abstract class Person { private String name; } // adds some properties specific to teachers public class Teacher extends Person { private int salary; } // adds some properties specific to students public class Student extends Person { private String course; } // adds some properties that apply to an entire group of people public class Result<T extends Person> { private List<T> group; private String city; // ... } We might have the following web service implementation annotated as follows: @WebService public class PersonService { @WebMethod public Result<Teacher> getTeachers() { ... } @WebMethod public Result<Student> getStudents() { ... } } The problem is that JAXB appears to marshall the Result object as a Result<Person> instead of the concrete type. So the Result returned by getTeachers() is serialized as containing a List<Person> instead of List<Teacher>, and the same for getStudents(), mutatis mutandis. Is this the expected behavior? Do I need to use @XmlSeeAlso on Person? Thanks! LES

    Read the article

  • .NET EventHandlers - Generic or no?

    - by Chris Marasti-Georg
    Every time I start in deep in a C# project, I end up with lots of events that really just need to pass a single item. I stick with the EventHandler/EventArgs practice, but what I like to do is have something like: public delegate void EventHandler<T>(object src, EventArgs<T> args); public class EventArgs<T>: EventArgs { private T item; public EventArgs(T item) { this.item = item; } public T Item { get { return item; } } } Later, I can have my public event EventHandler<Foo> FooChanged; public event EventHandler<Bar> BarChanged; However, it seems that the standard for .NET is to create a new delegate and EventArgs subclass for each type of event. Is there something wrong with my generic approach? EDIT: The reason for this post is that I just re-created this in a new project, and wanted to make sure it was ok. Actually, I was re-creating it as I posted. I found that there is a generic EventHandler<TEventArgs, so you don't need to create the generic delegate, but you still need the generic EventArgs<T class, because TEventArgs: EventArgs. Another EDIT: One downside (to me) of the built-in solution is the extra verbosity: public event EventHandler<EventArgs<Foo>> FooChanged; vs. public event EventHandler<Foo> FooChanged; It can be a pain for clients to register for your events though, because the System namespace is imported by default, so they have to manually seek out your namespace, even with a fancy tool like Resharper... Anyone have any ideas pertaining to that?

    Read the article

  • Java generic return type

    - by Colby77
    Hi, I'd like to write a method that can accept a type param (or whatever the method can figure out the type from) and return a value of this type so I don't have to cast the return type. Here is a method: public Object doIt(Object param){ if(param instanceof String){ return "string"; }else if(param instanceof Integer){ return 1; }else{ return null; } } When I call this method, and pass in it a String, even if I know the return type will be a String I have to cast the return Object. This is similar to the int param. How shall I write this method to accept a type param, and return this type?

    Read the article

  • Combine guava's ImmutableList and varargs

    - by Stas Kurilin
    I want create constructor that will take one or more integers and save it into field as ImmutableList. According to "The right way to use varargs to pass one or more arguments" by Bloch's Item 42 I create smt like class Foo{ private final ImmutableList<Integer> bar; public Foo(Integer first, Integer... other) { this.bar = ImmutableList.<Integer>builder() .add(first) .addAll(Arrays.asList(other)) .build(); } } Why builder doesn't get generic automatically? And, as it smells. How I can rewrite it?

    Read the article

  • how to use anonymous generic delegate in C# 2.0

    - by matti
    Hi. I have a class called NTree: class NTree<T> { public NTree(T data) { this.data = data; children = new List<NTree<T>>(); _stopTraverse = false; } ... public void Traverse(NTree<T> node, TreeVisitor<T> visitor) { try { _stopTraverse = false; Traverse(node, visitor); } finally { _stopTraverse = false; } } private void TraverseInternal(NTree<T> node, TreeVisitor<T> visitor) { if (_stopTraverse) return; if (!visitor(node.data)) { _stopTraverse = true; } foreach (NTree<T> kid in node.children) Traverse(kid, visitor); } When I try to use Traverse with anonymous delegate I get: Argument '2': cannot convert from 'anonymous method' to 'NisConverter.TreeVisitor' The code: tTable srcTable = new tTable(); DataRow[] rows; rootTree.Traverse(rootTree, delegate(TableRows tr) { if (tr.TableName == srcTable.mappingname) { rows = tr.Rows; return false; } }); This however produces no errors: static bool TableFinder<TableRows>(TableRows tr) { return true; } ... rootTree.Traverse(rootTree, TableFinder); I have tried to put "arrowhead-parenthisis" and everything to anonymous delegate but it just does not work. Please help me! Thanks & BR -Matti

    Read the article

  • Read-only view of a Java list with more general type parameter

    - by Michael Rusch
    Suppose I have class Foo extends Superclass. I understand why I can't do this: List<Foo> fooList = getFooList(); List<Superclass> supList = fooList; But, it would seem reasonable for me to do that if supList were somehow "read-only". Then, everything would be consistent as everything that would come out of an objList would be a Foo, which is a Superclass. I could probably write a List implementation that would take an underlying list and a more general type parameter, and would then return everything as the more general type instead of the specific type. It would work like the return of Collections.unmodifiableList() except that the type would be made more general. Is there an easier way? The reason I'm considering doing this is that I am implementing an interface that requires that I return an (unmodifiable) List<Superclass>, but internally I need to use Foos, so I have a List<Foo>. I can't just cast.

    Read the article

  • Struts2 <s:bean/> tag, used to instanciate a Parametric Bean

    - by Rasatavohary
    Hi, After looking a while other google, and the web, I decided to post my question here. The question is quite really basic, and simple : How do I use the struts2 tag <s:bean ... /> to instanciate a Parametric Bean ? For example imagine I have : public class GenericBean<T> { ... How will I instanciate this bean with a BeanType for instance, inside a jsp using struts 2 ? <s:bean name="GenericBean" var="myBean"/> Thanks you.

    Read the article

  • C# generic list <T> how to get the type of T?

    - by Daok
    Hello, Let say I have a List< T > abc = new List< T >; inside a class public class MyClass<T>//.... Later, when I initialize the class the T because MyTypeObject1. So I have a generic list of List< MyTypeObject1 >. I would like to know, what type of object the list of my class contain. Example, the list called abc contain what type of object? I cannot do abc[0].GetType(); because the list might contain 0 element. How can I do it?

    Read the article

  • Generic Property in C#

    - by ml123
    Hi, I'm not quite sure how to do that, but what I would like to do is to create a special type of property that will perform specific tasks at the get and set, and will be defined on generic type. For example, when writing this: MyProp<String name; a pre-defined get and set will be performed on the string value. How can that be done? Thanks!

    Read the article

  • How to do inclusive range queries when only half-open range is supported (ala SortedMap.subMap)

    - by polygenelubricants
    On SortedMap.subMap This is the API for SortedMap<K,V>.subMap: SortedMap<K,V> subMap(K fromKey, K toKey) : Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive. This inclusive lower bound, exclusive upper bound combo ("half-open range") is something that is prevalent in Java, and while it does have its benefits, it also has its quirks, as we shall soon see. The following snippet illustrates a simple usage of subMap: static <K,V> SortedMap<K,V> someSortOfSortedMap() { return Collections.synchronizedSortedMap(new TreeMap<K,V>()); } //... SortedMap<Integer,String> map = someSortOfSortedMap(); map.put(1, "One"); map.put(3, "Three"); map.put(5, "Five"); map.put(7, "Seven"); map.put(9, "Nine"); System.out.println(map.subMap(0, 4)); // prints "{1=One, 3=Three}" System.out.println(map.subMap(3, 7)); // prints "{3=Three, 5=Five}" The last line is important: 7=Seven is excluded, due to the exclusive upper bound nature of subMap. Now suppose that we actually need an inclusive upper bound, then we could try to write a utility method like this: static <V> SortedMap<Integer,V> subMapInclusive(SortedMap<Integer,V> map, int from, int to) { return (to == Integer.MAX_VALUE) ? map.tailMap(from) : map.subMap(from, to + 1); } Then, continuing on with the above snippet, we get: System.out.println(subMapInclusive(map, 3, 7)); // prints "{3=Three, 5=Five, 7=Seven}" map.put(Integer.MAX_VALUE, "Infinity"); System.out.println(subMapInclusive(map, 5, Integer.MAX_VALUE)); // {5=Five, 7=Seven, 9=Nine, 2147483647=Infinity} A couple of key observations need to be made: The good news is that we don't care about the type of the values, but... subMapInclusive assumes Integer keys for to + 1 to work. A generic version that also takes e.g. Long keys is not possible (see related questions) Not to mention that for Long, we need to compare against Long.MAX_VALUE instead Overloads for the numeric primitive boxed types Byte, Character, etc, as keys, must all be written individually A special check need to be made for toInclusive == Integer.MAX_VALUE, because +1 would overflow, and subMap would throw IllegalArgumentException: fromKey > toKey This, generally speaking, is an overly ugly and overly specific solution What about String keys? Or some unknown type that may not even be Comparable<?>? So the question is: is it possible to write a general subMapInclusive method that takes a SortedMap<K,V>, and K fromKey, K toKey, and perform an inclusive-range subMap queries? Related questions Are upper bounds of indexed ranges always assumed to be exclusive? Is it possible to write a generic +1 method for numeric box types in Java? On NavigableMap It should be mentioned that there's a NavigableMap.subMap overload that takes two additional boolean variables to signify whether the bounds are inclusive or exclusive. Had this been made available in SortedMap, then none of the above would've even been asked. So working with a NavigableMap<K,V> for inclusive range queries would've been ideal, but while Collections provides utility methods for SortedMap (among other things), we aren't afforded the same luxury with NavigableMap. Related questions Writing a synchronized thread-safety wrapper for NavigableMap On API providing only exclusive upper bound range queries Does this highlight a problem with exclusive upper bound range queries? How were inclusive range queries done in the past when exclusive upper bound is the only available functionality?

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >