Search Results

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

Page 16/41 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • What about optional generic type parameters in C# 5.0?

    - by Lars Corneliussen
    Just a thought. Wouldn't it be useful to have optional type parameters in C#? This would make life simpler. I'm tired of having multiple classes with the same name, but different type parameters. Also VS doesn't support this very vell (file names) :-) This would eliminate the need for a non-generic IEnumerable: interface IEnumerable<out T=object>{ IEnumerator<T> GetEnumerator() } What do you think?

    Read the article

  • adhoc struct/class in C#?

    - by acidzombie24
    Currently i am using reflection with sql. I find if i want to make a specialize query it is easiest to get the results by creating a new class inheriting from another and adding the 2 members/columns for my specialized query. Then due to reflections in the lib in my c# code i can write foreach(var v in list) { v.AnyMember and v.MyExtraMember) Now instead of having the class scattered around or modifying my main DB.cs file can i define a class inside a function? I know i can create an anonymous object by writing new {name=val, name2=...}; but i need a to pass this class in a generic function func(query, args);

    Read the article

  • Register and Resolve Generic Interfaces Unity

    - by user1643791
    I am trying to register some generic interfaces and resolve them . I have the registering function private static void RegisterFolderAssemblies(Type t,string folder) { var scanner = new FolderGenericInterfaceScanner(); var scanned = scanner.Scan(t,folder); // gets the implementations from a specific folder scanned.ForEach(concrete => { if (concrete.BaseType != null || concrete.IsGenericType) { myContainer.RegisterType(t, Type.GetType(concrete.AssemblyQualifiedName), concrete.AssemblyQualifiedName); } }); } which is called by the bootstrapper with RegisterFolderAssemblies(typeof(IConfigurationVerification<>),Environment.CurrentDirectory); The registration seem to go through ok but when I try to Resolve them with Type generic = typeof(IConfigurationVerification<>); Type specific = generic.MakeGenericType(input.Arguments[0].GetType()); var verifications = BootStrap.ResolveAll(specific); The input.Arguments[0] is an object of the type the generic is implemented in I also tried using typeof(IConfigurationVerification<) instead and get the same error . When ResolveAll is public static List<object> ResolveAll(Type t) { return myContainer.ResolveAll(t).ToList(); } I get a ResolutionFailedException with them message "The current type, Infrastructure.Interfaces.IConfigurationVerification`1[Infrastructure.Configuration.IMLogPlayerConfiguration+LoadDefinitions], is an interface and cannot be constructed. Are you missing a type mapping?" Any help will be great. Thanks in advance

    Read the article

  • Casting to generic type in Java doesn't raise ClassCastException?

    - by Kip
    I have come across a strange behavior of Java that seems like a bug. Is it? Casting an Object to a generic type (say, K) does not throw a ClassCastException even if the object is not an instance of K. Here is an example: import java.util.*; public final class Test { private static<K,V> void addToMap(Map<K,V> map, Object ... vals) { for(int i = 0; i < vals.length; i += 2) map.put((K)vals[i], (V)vals[i+1]); //Never throws ClassCastException! } public static void main(String[] args) { Map<String,Integer> m = new HashMap<String,Integer>(); addToMap(m, "hello", "world"); //No exception System.out.println(m.get("hello")); //Prints "world", which is NOT an Integer!! } }

    Read the article

  • Ambiguous Generic restriction T:class vs T:struct

    - by Maslow
    This code generates a compiler error that the member is already defined with the same parameter types. private T GetProperty<T>(Func<Settings, T> GetFunc) where T:class { try { return GetFunc(Properties.Settings.Default); } catch (Exception exception) { SettingReadException(this,exception); return null; } } private TNullable? GetProperty<TNullable>(Func<Settings, TNullable> GetFunc) where TNullable : struct { try { return GetFunc(Properties.Settings.Default); } catch (Exception ex) { SettingReadException(this, ex); return new Nullable<TNullable>(); } } Is there a clean work around?

    Read the article

  • Best way to translate from IDictionary to a generic IDictionary

    - by George Mauer
    I've got an IDictionary field that I would like to expose via a property of type IDictionary<string, dynamic> the conversion is surprisingly difficult since I have no idea what I can .Cast<>() the IDictionary to. Best I've got: IDictionary properties; protected virtual IDictionary<string, dynamic> Properties { get { return _properties.Keys.Cast<string>() .ToDictionary(name=>name, name=> _properties[name] as dynamic); } }

    Read the article

  • Generic type in generic collection

    - by Brian Triplett
    I have generic type that looks like: public class GenericClass<T, U> where T : IComparable<T> { // Class definition here } I then have a collection of these instances. What is the cleanest way to pass through the type constraints? public class GenericCollection<V> where V : GenericClass<T, U> // This won't compile { private GenericClass<T, U>[] entries; public V this[index] { get{ return this.entries[index]; } } } Is there perhaps a better way to design this? I think that specifying GenericCollection<T, U, V> where V : GenericClass<T, U> seems awkward. Might be my only option though....

    Read the article

  • Question concerning SCJP-6 exam

    - by abatishchev
    While preparing for the SCJP-6 exam I faced with a difficult issue. I can’t find answer by myself. Please, answer for the question and give short comments: abstract class A<K> extends Number> { // insert code here } public abstract <K> A<? extends Number> useMe(A<? super K> k); public abstract <K> A<? super Number> useMe(A<? extends K> k); public abstract <K> A<K> useMe(A<K> k); public abstract <V extends K> A<V> useMe(A<V> k); public abstract <V super K> A<V> useMe(A<V> k); public abstract <V extends Character> A<? super V> useMe(A<K> k); public abstract <V super Character> A<? super V> useMe(A<K> k); Which method can be inserted in a placeholder above? P.S. I tried to look on the specification. Those one was not helpful for me.

    Read the article

  • Converting non-generic List type to Generic List type in Java 1.5

    - by Shaun F
    I have a List that is guaranteed to contain just one type object. This is created by some underlying code in a library that I cannot update. I want to create a List<ObjectType> based on the incoming List object so that my calling code is talking to List<ObjectType>. What's the best way to convert the List (or any other object collection) to a List<ObjectType>.

    Read the article

  • Auto convert java source to use generic rather than raw types

    - by Sam
    Is there a way/tool to auto convert Java source code from using raw types to using generic types? I have some legacy code with 677 references to raw types: ArrayList 47 Vector 420 Hashtable 61 Enumeration 64 Class 7 Iterator 78 TOTAL 677 Now I could manually look through the code to infer the generic types and replace, but that is going to take a long time.

    Read the article

  • how to implement class with collection of string/object pairs so that an object can be returned with

    - by matti
    The values in a file are read as string and can be double, string or int or maybe even lists. An example file: DatabaseName=SomeBase Classes=11;12;13 IntValue=3 //this is required! DoubleValue=4.0 I was thinking something like this: public static T GetConfigValue(string cfgName) { // here we just return for example the value which could // be List[int] if parameter cfgName='Classes' // and LoadConfig was called with Dictionary containing // keyvaluepair 'Classes' / typeof(List[int]) } public static bool LoadConfig(Dictionary reqSettings, Dictionary optSettings) { foreach (KeyValuePair kvPair in reqSettings) { if (ReadCheckAndStore(kVPair, true)) return false; } foreach (KeyValuePair kvPair in reqSettings) { if (ReadCheckAndStore(kVPair, false)) return false; } return true; } private static bool ReadCheckAndStore(KeyValuePair kVPair, bool isRequired) { if (!ReadValue(kVPair.Key, out confValue) && isRequired) //req. IntValue !found return false; //here also have to test if read value is wanted type. //and if yes store to collection. } Thanks a lot & BR! -Matti PS. Additional issue is default values for optional settings. It's not elegant to pass them to LoadConfig in separate Dictionary, but that is an other issue...

    Read the article

  • Why does a function that takes IEnumerable<interface> not accept IEnumerable<class>?

    - by Matt Whitfield
    Say, for instance, I have a class: public class MyFoo : IMyBar { ... } Then, I would want to use the following code: List<MyFoo> classList = new List<MyFoo>(); classList.Add(new MyFoo(1)); classList.Add(new MyFoo(2)); classList.Add(new MyFoo(3)); List<IMyBar> interfaceList = new List<IMyBar>(classList); But this produces the error: `Argument '1': cannot convert from 'IEnumerable<MyFoo>' to 'IEnumerable<IMyBar>' Why is this? Since MyFoo implements IMyBar, one would expect that an IEnumerable of MyFoo could be treated as an IEnumerable of IMyBar. A mundane real-world example being producing a list of cars, and then being told that it wasn't a list of vehicles. It's only a minor annoyance, but if anyone can shed some light on this, I would be much obliged.

    Read the article

  • Creating circular generic references

    - by M. Jessup
    I am writing an application to do some distributed calculations in a peer to peer network. In defining the network I have two class the P2PNetwork and P2PClient. I want these to be generic and so have the definitions of: P2PNetwork<T extends P2PClient<? extends P2PNetwork<T>>> P2PClient<T extends P2PNetwork<? extends T>> with P2PClient defining a method of setNetwork(T network). What I am hoping to describe with this code is: A P2PNetwork is constituted of clients of a certain type A P2PClient may only belong to a network whose clients consist of the same type as this client (the circular-reference) This seems correct to me but if I try to create a non-generic version such as MyP2PClient<MyP2PNetwork<? extends MyP2PClient>> myClient; and other variants I receive numerous errors from the compiler. So my questions are as follows: Is a generic circular reference even possible (I have never seen anything explicitly forbidding it)? Is the above generic definition a correct definition of such a circular relationship? If it is valid, is it the "correct" way to describe such a relationship (i.e. is there another valid definition, which is stylistically preferred)? How would I properly define a non-generic instance of a Client and Server given the proper generic definition?

    Read the article

  • Convert a generic list to an array

    - by Freewind
    I have searched for this, but unfortunately, I don't get the correct answer. class Helper { public static <T> T[] toArray(List<T> list) { T[] array = (T[]) new Object[list.size()]; for (int i = 0; i < list.size(); i++) { array[i] = list.get(i); } return array; } } Test it: public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("abc"); String[] array = toArray(list); System.out.println(array); } But there is an error thrown: Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String; at test.Helper.main(Helper.java:30) How to solve this?

    Read the article

  • How to pass an IronPython instance method to a (C#) function parameter of type `Func<Foo>`

    - by Daren Thomas
    I am trying to assign an IronPython instance method to a C# Func<Foo> parameter. In C# I would have a method like: public class CSharpClass { public void DoSomething(Func<Foo> something) { var foo = something() } } And call it from IronPython like this: class IronPythonClass: def foobar(): return Foo() CSharpClass().DoSomething(foobar) But I'm getting the following error: TypeError: expected Func[Foo], got instancemethod

    Read the article

  • Getting the constructor of an Interface Type through reflection, is there a better approach than loo

    - by Will Marcouiller
    I have written a generic type: IDirectorySource<T> where T : IDirectoryEntry, which I'm using to manage Active Directory entries through my interfaces objects: IGroup, IOrganizationalUnit, IUser. So that I can write the following: IDirectorySource<IGroup> groups = new DirectorySource<IGroup>(); // Where IGroup implements `IDirectoryEntry`, of course.` foreach (IGroup g in groups.ToList()) { listView1.Items.Add(g.Name).SubItems.Add(g.Description); } From the IDirectorySource<T>.ToList() methods, I use reflection to find out the appropriate constructor for the type parameter T. However, since T is given an interface type, it cannot find any constructor at all! Of course, I have an internal class Group : IGroup which implements the IGroup interface. No matter how hard I have tried, I can't figure out how to get the constructor out of my interface through my implementing class. [DirectorySchemaAttribute("group")] public interface IGroup { } internal class Group : IGroup { internal Group(DirectoryEntry entry) { NativeEntry = entry; Domain = NativeEntry.Path; } // Implementing IGroup interface... } Within the ToList() method of my IDirectorySource<T> interface implementation, I look for the constructor of T as follows: internal class DirectorySource<T> : IDirectorySource<T> { // Implementing properties... // Methods implementations... public IList<T> ToList() { Type t = typeof(T) // Let's assume we're always working with the IGroup interface as T here to keep it simple. // So, my `DirectorySchema` property is already set to "group". // My `DirectorySearcher` is already instantiated here, as I do it within the DirectorySource<T> constructor. Searcher.Filter = string.Format("(&(objectClass={0}))", DirectorySchema) ConstructorInfo ctor = null; ParameterInfo[] params = null; // This is where I get stuck for now... Please see the helper method. GetConstructor(out ctor, out params, new Type() { DirectoryEntry }); SearchResultCollection results = null; try { results = Searcher.FindAll(); } catch (DirectoryServicesCOMException ex) { // Handling exception here... } foreach (SearchResult entry in results) entities.Add(ctor.Invoke(new object() { entry.GetDirectoryEntry() })); return entities; } } private void GetConstructor(out ConstructorInfo constructor, out ParameterInfo[] parameters, Type paramsTypes) { Type t = typeof(T); ConstructorInfo[] ctors = t.GetConstructors(BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.InvokeMethod); bool found = true; foreach (ContructorInfo c in ctors) { parameters = c.GetParameters(); if (parameters.GetLength(0) == paramsTypes.GetLength(0)) { for (int index = 0; index < parameters.GetLength(0); ++index) { if (!(parameters[index].GetType() is paramsTypes[index].GetType())) found = false; } if (found) { constructor = c; return; } } } // Processing constructor not found message here... } My problem is that T will always be an interface, so it never finds a constructor. Is there a better way than looping through all of my assembly types for implementations of my interface? I don't care about rewriting a piece of my code, I want to do it right on the first place so that I won't need to come back again and again and again. EDIT #1 Following Sam's advice, I will for now go with the IName and Name convention. However, is it me or there's some way to improve my code? Thanks! =)

    Read the article

  • Define Default constructor Structuremap in a Generic Repository

    - by Ricky
    Hello guys, I have a generic IRepository that has 2 constructors, one have none parameters, other has the datacontext as parameter. I want to define to structuremap to aways in this case use the parameterless constructor. I want a way to create a parameterless contructor, other solutions that I have seen, they create a new Datacontext and pass it to the constructor that has parameters.

    Read the article

  • How can I create object in abstract class without having knowledge of implementation?

    - by Greg
    Hi, Is there a way to implement the "CreateNode" method in my library abstract below? Or can this only be done in client code outside the library? I current get the error "Cannot create an instance of the abstract class or interface 'ToplogyLibrary.AbstractNode" public abstract class AbstractTopology<T> { // Properties public Dictionary<T, AbstractNode<T>> Nodes { get; private set; } public List<AbstractRelationship<T>> Relationships { get; private set; } // Constructors protected AbstractTopology() { Nodes = new Dictionary<T, AbstractNode<T>>(); } // Methods public AbstractNode<T> CreateNode() { var node = new AbstractNode<T>(); // ** Does not work ** Nodes.Add(node.Key, node); } } } public abstract class AbstractNode<T> { public T Key { get; set; } } public abstract class AbstractRelationship<T> { public AbstractNode<T> Parent { get; set; } public AbstractNode<T> Child { get; set; } }

    Read the article

  • To Reference A Generic Method With A Lambda Expression

    - by SDReyes
    It is possible to reference a generic method using a Lambda Expression Object? For example, having: TheObject: public abstract class LambdaExpression : Expression TheMethod (an extension method of LINQ): public static TSource Last<TSource>( this IEnumerable<TSource> source ) I'm trying to create an instance of TheObject, that references to TheMethod. How do you do such thing?

    Read the article

  • Casting Between Data Types in C#

    - by Jimbo
    I have (for example) an object of type A that I want to be able to cast to type B (similar to how you can cast an int to a float) Data types A and B are my own. Is it possible to define the rules by which this casting occurs? Example int a = 1; float b = (float)a; int c = (int)b;

    Read the article

  • [Java] 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 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: <K,V>doSomethingWithSomeMap(java.util.Map<K,V>,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

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >