Search Results

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

Page 25/41 | < Previous Page | 21 22 23 24 25 26 27 28 29 30 31 32  | Next Page >

  • GADTs and Scrap your Boilerplate

    - by finnsson
    I'm writing a XML (de)serializer using Text.XML.Light and Scrap your Boilerplate (at http://github.com/finnsson/Text.XML.Generic) and so far I got working code for "normal" ADTs but I'm stuck at deserializing GADTs. I got the GADT data DataBox where DataBox :: (Show d, Eq d, Data d) => d -> DataBox and I'm trying to get this to compile instance Data DataBox where gfoldl k z (DataBox d) = z DataBox `k` d gunfold k z c = k (z DataBox) -- not OK toConstr (DataBox d) = toConstr d dataTypeOf (DataBox d) = dataTypeOf d but I can't figure out how to implement gunfold for DataBox. The error message is Text/XML/Generic.hs:274:23: Ambiguous type variable `b' in the constraints: `Eq b' arising from a use of `DataBox' at Text/XML/Generic.hs:274:23-29 `Show b' arising from a use of `DataBox' at Text/XML/Generic.hs:274:23-29 `Data b' arising from a use of `k' at Text/XML/Generic.hs:274:18-30 Probable fix: add a type signature that fixes these type variable(s) It's complaining about not being able to figure out the data type of b. I'm also trying to implement dataCast1 and dataCast2 but I think I can live without them (i.e. an incorrect implementation). I guess my questions are: Is it possible to combine GADTs with Scrap your Boilerplate? If so: how do you implement gunfold for a GADT?

    Read the article

  • Can I Cast a Generic List by Type??

    - by CrazyJoe
    NavigatorItem NavItem = (NavigatorItem)cboItems.SelectedItem; lblTitle.Text = NavItem.Title; RadWrapPanel Panel = new RadWrapPanel(); Type t = NavItem.ItemsType; //<------ The Type inside my List is here. List<???> items = (List<???>)NavItem.Items; // <----Here Is the problem foreach (object item in items) { Panel.Children.Add((UIElement)Activator.CreateInstance(NavItem.Display,item)); } ItemsContainer.Content = Panel; In code above i need to get the type of items on t variable to put into of my generic List. Help Please!!!

    Read the article

  • inconsistency between Sun JRE javac and Eclipse java compiler?

    - by Jason S
    This confuses me. The following compiles fine under Eclipse. package com.example.gotchas; public class GenericHelper1 { static <T> T fail() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** * just calls fail() * @return something maybe */ public boolean argh() { return fail(); } public static void main(String[] args) { // TODO Auto-generated method stub } } But if I try to do a clean build with ant, or at the command line with javac, I get this: src\com\example\gotchas\GenericHelper1.java:14: type parameters of <T>T cannot be determined; no unique maximal instance exists for type variable T with upper bounds boolean,java.lang.Object public boolean argh() { return fail(); } ^ 1 error what gives, and how do I fix it?

    Read the article

  • Multiple generic types in one container

    - by Lirik
    I was looking at the answer of this question regarding multiple generic types in one container and I can't really get it to work: the properties of the Metadata class are not visible, since the abstract class doesn't have them. Here is a slightly modified version of the code in the original question: public abstract class Metadata { } public class Metadata<T> : Metadata { // ... some other meta data public T Function{ get; set; } } List<Metadata> metadataObjects; metadataObjects.Add(new Metadata<Func<double,double>>()); metadataObjects.Add(new Metadata<Func<int,double>>()); metadataObjects.Add(new Metadata<Func<double,int>>()); foreach( Metadata md in metadataObjects) { var tmp = md.Function; // <-- Error: does not contain a definition for Function } The exact error is: error CS1061: 'Metadata' does not contain a definition for 'Function' and no extension method 'Function' accepting a first argument of type 'Metadata' could be found (are you missing a using directive or an assembly reference?) I believe it's because the abstract class does not define the property Function, thus the whole effort is completely useless. Is there a way that we can get the properties?

    Read the article

  • [VB.Net] Typecasting generic parameters.

    - by CFP
    Hello world! Using the following code: Function GetSetting(Of T)(ByVal SettingName As String, ByRef DefaultVal As T) As T Return If(Configuration.ContainsKey(SettingName), CType(Configuration(SettingName), T), DefaultVal) End Function Yields the following error: Value of type 'String' cannot be converted to 'T'. Any way I could specify that in all cases, the conversion will indeed be possible (I'm basically getting integers, booleans, doubles and strings). Thanks!

    Read the article

  • How do I create a generic method with a generic in the where clause? (Man that's clear as mud!)

    - by Jordan
    Is there a way of doing this: protected void SubscribeToEvent<TEvent, TPayload>(Action<TPayload> a_action) where TEvent : CompositePresentationEvent<TPayload> { TEvent newEvent = _eventAggregator.GetEvent<TEvent>(); SubscriptionToken eventToken = newEvent.Subscribe(a_action); _lstEventSubscriptions.Add(new KeyValuePair<EventBase, SubscriptionToken>(newEvent, eventToken)); } without requiring the user to specify a TPayload parameter?

    Read the article

  • Generic Constraints And Type Parameters Mess

    - by Dummy01
    Hi everyone, I have the following base abstract class defined as: public abstract class BaseObject<T> : IComparable, IComparable<T>, IEquatable<T> {} I also have an interface defined as: public interface ICode<T> where T : struct { T Code { get; } } Now I want to derive a class that is inherited from BaseObject<T> and includes interface ICode<T>. I tried to define it like that: public class DerivedObject<T, U> : BaseObject<T>, ICode<U> where T : DerivedObject<T, U> where U : struct { public DerivedObject(U code) { Code = code; } // From BaseObject protected override int InstanceCompareTo(T obj) { return Code.CompareTo(obj.Code); } // From BaseObject protected override bool InstanceEquals(T obj) { return Code.Equals(obj.Code); } // From ICode U _Code; public U Code { get { return _Code; } protected set { _Code = value; } } } The only error that comes from the compiler is for Code.CompareTo(obj.Code) with the message: 'U' does not contain a definition for 'CompareTo' and no extension method 'CompareTo' accepting a first argument of type 'U' could be found. But U is a value type and should know CompareTo. Have you any idea what I am doing wrong, or if I do all wrong? My final aim is to derive classes such these: public class Account : DerivedObject<Account, int> public class ItemGroup : DerivedObject<ItemGroup, string> Big Thanks In Advance!

    Read the article

  • Class<T> and static method Class.forName() drive me crazy.

    - by matt
    Hi, this code doesn't compile. I'm wondering what I am doing wrong: private static Importable getRightInstance(String s) throws Exception { Class<Importable> c = Class.forName(s); Importable i = c.newInstance(); return i; } where Importable is an interface and the string s is the name of an implementing class. The compiler says: ./Importer.java:33: incompatible types found : java.lang.Class<capture#964 of ?> required: java.lang.Class<Importable> Class<Importable> c = Class.forName(format(s)); thanks for any help! All the solutions Class<? extends Importable> c = Class.forName(s).asSubclass(Importable.class); and Class<? extends Importable> c = (Class<? extends Importable>) Class.forName(s); and Class<?> c = Class.forName(format(s)); Importable i = (Importable)c.newInstance(); give this error: Exception in thread "main" java.lang.IncompatibleClassChangeError: class C1 has interface Importable as super class where C1 is effectively a class implementing Importable, one of those i want to cast to Importable.

    Read the article

  • Generic TypeIdenitifier convertion.How?

    - by John
    How do I convert the TypeIdenitifier to a class type? I need to use implicit convertion. type TMyChildArray<T>=class(TMyArray<T>) private FData:Array of T; procedure AddEnd(); end; TTypeIdenitifierParentClass=class(TAnotherParentClass) protected TestField:Cardinal; end; procedure TMyChildArray<T>.AddEnd(); var elem:T; begin for elem in Fdata do TTypeIdenitifierParentClass(elem).TestField:=0; end; I get "Invalid typecast" on the implicit convertion "TTypeIdenitifierParentClass(elem).TestField:=0;". The principle I want to use is that the TypeIdenitifier will represent a class that descends from TTypeIdenitifierParentClass.There are many class types,but all of them descend that class. How do I do this?

    Read the article

  • Where are the function literals c++?

    - by academicRobot
    First of all, maybe literals is not the right term for this concept, but its the closest I could think of (not literals in the sense of functions as first class citizens). The idea is that when you make a conventional function call, it compiles to something like this: callq <immediate address> But if you make a function call using a function pointer, it compiles to something like this: mov <memory location>,%rax callq *%rax Which is all well and good. However, what if I'm writing a template library that requires a callback of some sort with a specified argument list and the user of the library is expected to know what function they want to call at compile time? Then I would like to write my template to accept a function literal as a template parameter. So, similar to template <int int_literal> struct my_template {...};` I'd like to write template <func_literal_t func_literal> struct my_template {...}; and have calls to func_literal within my_template compile to callq <immediate address>. Is there a facility in C++ for this, or a work around to achieve the same effect? If not, why not (e.g. some cataclysmic side effects)? How about C++0x or another language? Solutions that are not portable are fine. Solutions that include the use of member function pointers would be ideal. I'm not particularly interested in being told "You are a <socially unacceptable term for a person of low IQ>, just use function pointers/functors." This is a curiosity based question, and it seems that it might be useful in some (albeit limited) applications. It seems like this should be possible since function names are just placeholders for a (relative) memory address, so why not allow more liberal use (e.g. aliasing) of this placeholder. p.s. I use function pointers and functions objects all the the time and they are great. But this post got me thinking about the don't pay for what you don't use principle in relation to function calls, and it seems like forcing the use of function pointers or similar facility when the function is known at compile time is a violation of this principle, though a small one.

    Read the article

  • WCF: get generic type object (e.g. MyObject<T>) from remote machine

    - by Aaron
    I have two applications that are communicating through WCF. On the server the following object exists: public class MyObject<T> { ... public Entry<T> GetValue() } Where Entry<T> is another object with T Data as a public property. T could be any number of types (string, double, etc) On the client I have ClientObject<T> that needs to get the value of Data from the server (same type). Since I'm using WCF, I have to define my ServiceContract as an interface, and I can't have ClientObject<T> call Entry<T> GetMyObjectValue (string Name) which calls GetValue on the correct MyObject<T> because my interface isn't aware of the type information. I've tried implementing separate GetValue functions (GetMyObjectValueDouble, GetMyObjectValueString) in the interface and then have ClientObject determine the correct one to call. However, Entry<T> val = (Entry<T>)GetMyObjectValueDouble(...); doesn't work because it's not sure about the type information. How can I go about getting a generic object over WCF with the correct type information? Let me know if there are other details I can provide. Thanks!

    Read the article

  • Getting class Type information for Elements on a collection

    - by DutrowLLC
    I would like to get gain access to the type of Object held in a Collection. Below is a simplified example of when and why I might want to do this. Is this even possible? List<Address> addressList = new LinkedList<Address>(); Main.addElement(addressList); Class Main{ public void addElement(Object inArgument){ List<Object> argument = (List<Object>)inArgument; argument.add( /* WOULD LIKE TO CREATE A NEW OBJECT OF THE APPROPRIATE TYPE HERE, IN THIS CASE, IT WOULD BE OF TYPE: "Address" */ ); } }

    Read the article

  • Accessing properties through Generic type parameter

    - by Veer
    I'm trying to create a generic repository for my models. Currently i've 3 different models which have no relationship between them. (Contacts, Notes, Reminders). class Repository<T> where T:class { public IQueryable<T> SearchExact(string keyword) { //Is there a way i can make the below line generic //return db.ContactModels.Where(i => i.Name == keyword) //I also tried db.GetTable<T>().Where(i => i.Name == keyword) //But the variable i doesn't have the Name property since it would know it only in the runtime //db also has a method ITable GetTable(Type modelType) but don't think if that would help me } } In MainViewModel, I call the Search method like this: Repository<ContactModel> _contactRepository = new Repository<ContactModel>(); public void Search(string keyword) { var filteredList = _contactRepository.SearchExact(keyword).ToList(); } I use Linq-To-Sql.

    Read the article

  • C# Reflection Question

    - by Jimbo
    This is a scenario created to help understand what Im trying to achieve. I am trying to create a method that returns the specified property of a generic object e.g. public object getValue<TModel>(TModel item, string propertyName) where TModel : class{ PropertyInfo p = typeof(TModel).GetProperty(propertyName); return p.GetValue(item, null); } The code above works fine if you're looking for a property on the TModel item e.g. string customerName = getValue<Customer>(customer, "name"); However, if you want to find out what the customer's group's name is, it becomes a problem: e.g. string customerGroupName = getValue<Customer>(customer, "Group.name"); Hoping someone can give me some insight on this way out scenario - thanks.

    Read the article

  • .net Generic Calls <T>

    - by Ryan
    I have a function that accepts a generic parameter T that is of type class like so : public Func<T, bool> MyMethod<T>(string paramName, object value) where T : class But when calling the function I do not have direct access to the class that needs to be the parameter. MyMethod<foo>("foo1", "foo2") Is there a way I can get the class foo via other means like reflection so I can use the function?

    Read the article

  • Exporting to CSV with dynamic field type handling

    - by serhio
    I have to do an export from DB to CSV. field; fileld; field... etc Have 3 types of fields: Alpha, Numeric and Bool respresented as "alphaValue",intValue and True/False. I try to encapsulate this in a fields collection, in order to export if alpha then set "", if Bool=True/False if numeric let as is. and try to build a CsvField class: Public Structure?Class CsvField(Of T As ???) End Structure Enum FieldType Alpha Bool Numeric End Enum any suggestions welcomed.

    Read the article

  • Namespace scoped aliases for generic types in C#

    - by TN
    Let's have a following example: public class X { } public class Y { } public class Z { } public delegate IDictionary<Y, IList<Z>> Bar(IList<X> x, int i); public interface IFoo { // ... Bar Bar { get; } } public class Foo : IFoo { // ... public Bar Bar { get { return null; //... } } } void Main() { IFoo foo; //= ... IEnumerable<IList<X>> source; //= ... var results = source.Select(foo.Bar); } The compiler says: The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly. It's because, it cannot convert Bar to Func<IList<X>, int, IDictionary<Y, IList<Z>>>. It would be great if I could create type namespace scoped type aliases for generic types in C#. Then I would define Bar not as a delegate, but rather I would define it as an namespace scoped alias for Func<IList<X>, int, IDictionary<Y, IList<Z>>>. public alias Bar = Func<IList<X>, int, IDictionary<Y, IList<Z>>>; I could then also define namespace scoped alias for e.g. IDictionary<Y, IList<Z>>. And if used appropriately:), it will make the code more readable. Now I have inline the generic types and the real code is not well readable:( Have you find the same trouble:)? Is there any good reason why it is not in C# 3.0? Or there is no good reason, it's just matter of money and/or time? EDIT: I know that I can use using, but it is not namespace based - not so convenient for my case.

    Read the article

  • Java compiler rejects variable declaration with parameterized inner class

    - by Johansensen
    I have some Groovy code which works fine in the Groovy bytecode compiler, but the Java stub generated by it causes an error in the Java compiler. I think this is probably yet another bug in the Groovy stub generator, but I really can't figure out why the Java compiler doesn't like the generated code. Here's a truncated version of the generated Java class (please excuse the ugly formatting): @groovy.util.logging.Log4j() public abstract class AbstractProcessingQueue <T> extends nz.ac.auckland.digitizer.AbstractAgent implements groovy.lang.GroovyObject { protected int retryFrequency; protected java.util.Queue<nz.ac.auckland.digitizer.AbstractProcessingQueue.ProcessingQueueMember<T>> items; public AbstractProcessingQueue (int processFrequency, int timeout, int retryFrequency) { super ((int)0, (int)0); } private enum ProcessState implements groovy.lang.GroovyObject { NEW, FAILED, FINISHED; } private class ProcessingQueueMember<E> extends java.lang.Object implements groovy.lang.GroovyObject { public ProcessingQueueMember (E object) {} } } The offending line in the generated code is this: protected java.util.Queue<nz.ac.auckland.digitizer.AbstractProcessingQueue.ProcessingQueueMember<T>> items; which produces the following compile error: [ERROR] C:\Documents and Settings\Administrator\digitizer\target\generated-sources\groovy-stubs\main\nz\ac\auckland\digitizer\AbstractProcessingQueue.java:[14,96] error: improperly formed type, type arguments given on a raw type The column index of 96 in the compile error points to the <T> parameterization of the ProcessingQueueMember type. But ProcessingQueueMember is not a raw type as the compiler claims, it is a generic type: private class ProcessingQueueMember <E> extends java.lang.Object implements groovy.lang.GroovyObject { ... I am very confused as to why the compiler thinks that the type Queue<ProcessingQueueMember<T>> is invalid. The Groovy source compiles fine, and the generated Java code looks perfectly correct to me too. What am I missing here? Is it something to do with the fact that the type in question is a nested class? (in case anyone is interested, I have filed this bug report relating to the issue in this question) Edit: Turns out this was indeed a stub compiler bug- this issue is now fixed in 1.8.9, 2.0.4 and 2.1, so if you're still having this issue just upgrade to one of those versions. :)

    Read the article

  • Retrieving the MethodInfo of of the correct overload of a generic method

    - by Anne
    I have this type that contains two overloads of a generic method. I like to retrieve one of the overloads (with the Func<T> parameter) using reflection. The problem however is that I can't find the correct parameter type to supply the Type.GetMethod(string, Type[]) method with. Here is my class definition: public class Foo { public void Bar<T>(Func<T> f) { } public void Bar<T>(Action<T> a) { } } And this is what I've come up with, unfortunately without succes: [TestMethod] public void Test1() { Type parameterType = typeof(Func<>); var method = typeof(Foo).GetMethod("Bar", new Type[] { parameterType }); Assert.IsNotNull(method); // Fails } How can I get the MethodInfo of a generic method of which I know the parameters?

    Read the article

  • Returnimng collection of interfaces

    - by apoorv020
    I have created the following interface public interface ISolutionSpace { public boolean isFeasible(); public boolean isSolution(); public Set<ISolutionSpace> generateChildren(); } However, in the implementation of ISolutionSpace in a class called EightQueenSolutionSpace, I am going to return a set of EightQueenSolutionSpace instances, like the following stub: @Override public Set<ISolutionSpace> generateChildren() { return new HashSet<EightQueenSolutionSpace>(); } However this stub wont compile. What changes do I need to make? EDIT: I tried 'HashSet' as well and had tried using the extends keyword. However since 'ISolutionSpace' is an interface and EightQueenSolutionSpace is an implementation(and not a subclass) of 'ISolutionSpace', it is still not working.

    Read the article

  • Method not being resolved for dynamic generic type

    - by kelloti
    I have these types: public class GenericDao<T> { public T Save(T t) { return t; } } public abstract class DomainObject { // Some properties protected abstract dynamic Dao { get; } public virtual void Save() { var dao = Dao; dao.Save(this); } } public class Attachment : DomainObject { protected dynamic Dao { get { return new GenericDao<Attachment>(); } } } Then when I run this code it fails with RuntimeBinderException: Best overloaded method match for 'GenericDAO<Attachment.Save(Attachment)' has some invalid arguments var obj = new Attachment() { /* set properties */ }; obj.Save(); I've verified that in DomainObject.Save() "this" is definitely Attachment, so the error doesn't really make sense. Can anyone shed some light on why the method isn't resolving? Some more information - It succeeds if I change the contents of DomainObject.Save() to use reflection: public virtual void Save() { var dao = Dao; var type = dao.GetType(); var save = ((Type)type).GetMethod("Save"); save.Invoke(dao, new []{this}); }

    Read the article

  • can I have an abstract base class with the key attribute being generic

    - by Greg
    Hi, I want to create a re-usable library. I was going to use extension methods however I run into some issues in some cases for the client to have to specify in the calling method the types. QUESTION - If I use an abstract base class as the basis, can I specify an attribute/property in the class to be generic (e.g. the key property might be an 'int' in one case, or a 'string' in another)?

    Read the article

  • C# ambiguity in Func + extension methods + lambdas

    - by Hobbes
    I've been trying to make my way through this article: http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx ... And something on page 1 made me uncomfortable. In particular, I was trying to wrap my head around the Compose<() function, and I wrote an example for myself. Consider the following two Func's: Func<double, double> addTenth = x => x + 0.10; Func<double, string> toPercentString = x => (x * 100.0).ToString() + "%"; No problem! It's easy to understand what these two do. Now, following the example from the article, you can write a generic extension method to compose these functions, like so: public static class ExtensionMethods { public static Func<TInput, TLastOutput> Compose<TInput, TFirstOutput, TLastOutput>( this Func<TFirstOutput, TLastOutput> toPercentString, Func<TInput, TFirstOutput> addTenth) { return input => toPercentString(addTenth(input)); } } Fine. So now you can say: string x = toPercentString.Compose<double, double, string>(addTenth)(0.4); And you get the string "50%" So far, so good. But there's something ambiguous here. Let's say you write another extension method, so now you have two functions: public static class ExtensionMethods { public static Func<TInput, TLastOutput> Compose<TInput, TFirstOutput, TLastOutput>( this Func<TFirstOutput, TLastOutput> toPercentString, Func<TInput, TFirstOutput> addTenth) { return input => toPercentString(addTenth(input)); } public static Func<double, string> Compose<TInput, TFirstOutput, TLastOutput>(this Func<double, string> toPercentString, Func<double, double> addTenth) { return input => toPercentString(addTenth(input + 99999)); } } Herein is the ambiguity. Don't these two function have overlapping signatures? Yes. Does this even compile? Yes. Which one get's called? The second one (which clearly gives you the "wrong" result) gets called. If you comment out either function, it still compiles, but you get different results. It seems like nitpicking, but there's something that deeply offends my sensibilities here, and I can't put my finger on it. Does it have to do with extension methods? Does it have to do with lambdas? Or does it have to do with how Func< allows you to parameterize the return type? I'm not sure. I'm guessing that this is all addressed somewhere in the spec, but I don't even know what to Google to find this. Help!

    Read the article

  • How to specify generic method type parameters partly

    - by DNNX
    I have an extension method like below: public static T GetValueAs<T, R>(this IDictionary<string, R> dictionary, string fieldName) where T : R { R value; if (!dictionary.TryGetValue(fieldName, out value)) return default(T); return (T)value; } Currently, I can use it in the following way: var dictionary = new Dictionary<string, object(); //... var list = dictionary.GetValueAs<List<int, object("A"); // this may throw ClassCastException - this is expected behavior; It works pretty fine, but the second type parameter is really annoying. Is it possible in C# 4.0 rewrite GetValueAs is such a way that the method will still be applicable to different types of string-keyed dictionaries AND there will be no need to specify second type parameter in the calling code, i.e. use var list = dictionary.GetValueAs<List<int("A"); or at least something like var list = dictionary.GetValueAs<List<int, ?("A"); instead of var list = dictionary.GetValueAs<List<int, object("A");

    Read the article

< Previous Page | 21 22 23 24 25 26 27 28 29 30 31 32  | Next Page >