Search Results

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

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

  • How can I make the C# compiler infer these type parameters automatically?

    - by John Feminella
    I have some code that looks like the following. First I have some domain classes and some special comparators for them. public class Fruit { public int Calories { get; set; } public string Name { get; set; } } public class FruitEqualityComparer : IEqualityComparer<Fruit> { // ... } public class BasketEqualityComparer : IEqualityComparer<IEnumerable<Fruit>> { // ... } Next, I have a helper class called ConstraintChecker. It has a simple BaseEquals method that makes sure some simple base cases are considered: public static class ConstraintChecker { public static bool BaseEquals(T lhs, T rhs) { bool sameObject = l == r; bool leftNull = l == null; bool rightNull = r == null; return sameObject && !leftNull && !rightNull; } There's also a SemanticEquals method which is just a BaseEquals check and a comparator function that you specify. public static bool SemanticEquals<T>(T lhs, T rhs, Func<T, T, bool> f) { return BaseEquals(lhs, rhs) && f(lhs, rhs); } And finally there's a SemanticSequenceEquals method which accepts two IEnumerable<T> instances to compare, and an IEqualityComparer instance that will get called on each pair of elements in the list via Enumerable.SequenceEquals. public static bool SemanticSequenceEquals<T, U, V>(U lhs, U rhs, V comparator) where U : IEnumerable<T> where V : IEqualityComparer<T> { return SemanticEquals(lhs, rhs, (l, r) => lhs.SequenceEqual(rhs, comparator)); } } // end of ConstraintChecker The point of SemanticSequenceEquals is that you don't have to define two comparators whenever you want to compare both IEnumerable<T> and T instances; now you can just specify an IEqualityComparer<T> and it will also handle lists when you invoke SemanticSequenceEquals. So I could get rid of the BasketEqualityComparer class, which would be nice. But there's a problem. The C# compiler can't figure out the types involved when you invoke SemanticSequenceEquals: return ConstraintChecker.SemanticSequenceEquals(lhs, rhs, new FruitEqualityComparer()); If I specify them explicitly, it works: return ConstraintChecker.SemanticSequenceEquals< Fruit, IEnumerable<Fruit>, IEqualityComparer<Fruit> > (lhs, rhs, new FruitEqualityComparer()); What can I change here so that I don't have to write the type parameters explicitly?

    Read the article

  • Java enums in generic type

    - by Marcin Cylke
    Hi, I'd like to create a generic enum-based mapper for IBatis. I'm doing this with the below code. This does have compile time errors, which I don't know how to fix. Maybe my solution is just plain wrong (keep in mind the use of IBatis), in such case please suggest something better. Any help appreciated. What I want to achieve is to define subsequent mappers as: public class XEnumTypeHandler extends CommonEnumTypeHandler<X> { } The current code: public class CommonEnumTypeHandler<T extends Enum> implements TypeHandlerCallback { public void setParameter(ParameterSetter ps, Object o) throws SQLException { if (o.getClass().isAssignableFrom(**T**)) { ps.setString(((**T**) o).value().toUpperCase()); } else throw new SQLException("Excpected ParameterType object than: " + o); } public Object getResult(ResultGetter rs) throws SQLException { Object o = valueOf(rs.getString()); if (o == null) throw new SQLException("Unknown parameter type: " + rs.getString()); return o; } public Object valueOf(String s) { for (T pt : T.**values()**) { if (pt.**value()**.equalsIgnoreCase(s)) return pt; } return null; } } I've added error markings to the above code, the error messages are in order: T cannot be resolved The method value() is undefined for the type T The method values() is undefined for the type T The method values() is undefined for the type T

    Read the article

  • What is the "Dispatcher" design pattern?

    - by Ben Farmer
    What is the "dispatcher" pattern and how would I implement it in code? I have a property bag of generic objects and would like to have the retrieval delegated to a generic method. Currently, I have properties looking for a specific key in the bag. For example: private Dictionary<String, Object> Foo { get; set; } private const String WidgetKey = "WIDGETKEY"; public Widget? WidgetItem { get { return Foo.ContainsKey(WidgetKey) ? Foo[WidgetKey] as Widget: null; } set { if (Foo.ContainsKey(WidgetKey)) Foo[WidgetKey] = value; else Foo.Add(WidgetKey, value); } } It was suggested that this could be more generic with the "dispatcher" pattern, but I've been unable to find a good description or example. I'm looking for a more generic way to handle the property bag store/retrieve.

    Read the article

  • Is there a way to achieve covariance of generic types in C# 3.0?

    - by nullDev
    This has been introduced in C# 4.0, but is there a way to achieve this in c# 3.0? For e.g., consider the following code: class Base { } class Derived1 : Base { } class Derived2 : Base { } class User<T> where T : Base { } class User1 : User<Derived1> { } Now, I would like to have a list of User<T>, in which I can store User<Derived1> as well as User<Derived2>, but the following code fails to compile in C# 3.0: List<User<Base>> users = new List<User<Base>>(); users.Add(new User1()); Any ideas?

    Read the article

  • Casting Generic Types

    - by David Rutten
    Public Function CastToT(Of T)(ByVal GenericType(Of Object) data) As GenericType(Of T) Return DirectCast(data, GenericType(Of T)) End Function The above clearly does not work. Is there any way to perform this cast if I know that all objects inside data are in fact of Type T?

    Read the article

  • Extending both T and SomeInterface<T> in Java

    - by Graeme Moss
    I want to create a class that takes two parameters. One should be typed simply as T. The other should be typed as something that extends both T and SomeInterface. When I attempt this with public class SomeClass<T, S extends SomeInterface<T> & T> then Java complains with "The type T is not an interface; it cannot be specified as a bounded parameter" and if instead I attempt to create an interface for S with public interface TandSomeInterface<T> extends SomeInterface<T>, T then Java complains with "Cannot refer to the type parameter T as a supertype" Is there any way to do this in Java? I think you can do it in C++...?

    Read the article

  • Java map with values limited by key's type parameter

    - by Ashley Mercer
    Is there a way in Java to have a map where the type parameter of a value is tied to the type parameter of a key? What I want to write is something like the following: public class Foo { // This declaration won't compile - what should it be? private static Map<Class<T>, T> defaultValues; // These two methods are just fine public static <T> void setDefaultValue(Class<T> clazz, T value) { defaultValues.put(clazz, value); } public static <T> T getDefaultValue(Class<T> clazz) { return defaultValues.get(clazz); } } That is, I can store any default value against a Class object, provided the value's type matches that of the Class object. I don't see why this shouldn't be allowed since I can ensure when setting/getting values that the types are correct. EDIT: Thanks to cletus for his answer. I don't actually need the type parameters on the map itself since I can ensure consistency in the methods which get/set values, even if it means using some slightly ugly casts.

    Read the article

  • Do I have to allocate and free records when using TList<T> in Delphi?

    - by afrazier
    The question more or less says it all. Given the following record structure: type TPerson = record Name: string; Age: Integer; end; PPerson = ^TPerson; TPersonList = TList<TPerson>; Is the following code valid? procedure ReadPeople(DataSet: TDataSet; PersonList: TPersonList); begin PersonList.Count := DataSet.RecordCount; if DataSet.RecordCount = 0 then Exit; DataSet.First; while not DataSet.Eof do begin PersonList[DataSet.RecNo].Name := DataSet.FieldByName('Name').AsString; PersonList[DataSet.RecNo].Age := DataSet.FieldByName('Age').AsInteger; DataSet.Next; end; end; Do I have to use GetMem/FreeMem to allocate and free records an instance of TPersonList, or am I free to directly access the TPersonList entries directly? My gut says that the code should be valid, though I'm not sure if there's any wrinkles related to record initialization or finalization.

    Read the article

  • Why does this return zero results?

    - by Jon
    I have a List<List<string>> and when I try to search with the List<string> it returns no results. Any ideas? Thanks List<List<string>> test = new List<List<string>>(); List<string> ff = new List<string>(); ff.Add("1"); ff.Add("ABC 1"); test.Add(ff); ff = new List<string>(); ff.Add("2"); ff.Add("ABC 2"); test.Add(ff); var result = test.Where(x=>x.Contains("ABC")); //result.Count(); is 0

    Read the article

  • How to define generic super type for static factory method?

    - by Esko
    If this has already been asked, please link and close this one. I'm currently prototyping a design for a simplified API of a certain another API that's a lot more complex (and potentially dangerous) to use. Considering the related somewhat complex object creation I decided to use static factory methods to simplify the API and I currently have the following which works as expected: public class Glue<T> { private List<Type<T>> types; private Glue() { types = new ArrayList<Type<T>>(); } private static class Type<T> { private T value; /* some other properties, omitted for simplicity */ public Type(T value) { this.value = value; } } public static <T> Glue<T> glueFactory(String name, T first, T second) { Glue<T> g = new Glue<T>(); Type<T> firstType = new Glue.Type<T>(first); Type<T> secondType = new Glue.Type<T>(second); g.types.add(firstType); g.types.add(secondType); /* omitted complex stuff */ return g; } } As said, this works as intended. When the API user (=another developer) types Glue<Horse> strongGlue = Glue.glueFactory("2HP", new Horse(), new Horse()); he gets exactly what he wanted. What I'm missing is that how do I enforce that Horse - or whatever is put into the factory method - always implements both Serializable and Comparable? Simply adding them to factory method's signature using <T extends Comparable<T> & Serializable> doesn't necessarily enforce this rule in all cases, only when this simplified API is used. That's why I'd like to add them to the class' definition and then modify the factory method accordingly. PS: No horses (and definitely no ponies!) were harmed in writing of this question.

    Read the article

  • Generic Dictionary C#

    - by pm_2
    I have a class that inherits from a generic dictionary as follows: Class myClass : System.Collections.Generic.Dictionary<int, Object> I have added a list of values to this in a particular order, but I now wish to change that order. Is there any way (without removing and re-adding) that I could effectively re-index the values; so change the object at index 1 to now be at index 10 for example? For example, this doesn't work: myClass[1].Index = 10;

    Read the article

  • What should I name my files with generic class definitions?

    - by Tomas Lycken
    I'm writing a couple of classes that all have generic type arguments, but I need to overload the classes because I need a different number of arguments in different scenarios. Basically, I have public class MyGenericClass<T> { ... } public class MyGenericClass<T, K> { ... } public class MyGenericClass<T, K, L> { ... } // it could go on forever, but it won't... I want them all in the same namespace, but in one source file per class. What should I name the files? Is there a best practice?

    Read the article

  • Generic overriding tells me this is the same function. Not agree.

    - by serhio
    base class: Class List(Of T) Function Contains(ByVal value As T) As Boolean derived class: Class Bar : List(Of Exception) ' Exception type as example ' Function Contains(Of U)(ByVal value As U) As Boolean compiler tells me that that two are the same, so I need to declare Overloads/new this second function. But I want use U to differentiate the type (one logic) like NullReferenceException, ArgumentNull Exception, etc. but want to leave the base function(no differentiation by type - other logic) as well.

    Read the article

  • Unchecked call to compareTo

    - by Dave Jarvis
    Background Create a Map that can be sorted by value. Problem The code executes as expected, but does not compile cleanly: http://pastebin.com/bWhbHQmT The syntax for passing Comparable as a generic parameter along to the Map.Entry<K, V> (where V must be Comparable?) -- so that the (Comparable) typecast shown in the warning can be dropped -- eludes me. Warning Compiler's cantankerous complaint: SortableValueMap.java:24: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable return ((Comparable)entry1.getValue()).compareTo( entry2.getValue() ); Question How can the code be changed to compile without any warnings (without suppressing them while compiling with -Xlint:unchecked)? Related TreeMap sort by value How to sort a Map on the values in Java? http://paaloliver.wordpress.com/2006/01/24/sorting-maps-in-java/ Thank you!

    Read the article

  • Hot to get generic type from object type

    - by Murat
    My Classes are; class BaseClass { } class DerivedClass1 : BaseClass { } class GenericClass<T> { } class DerivedClass2 : BaseClass { GenericClass<DerivedClass1> subItem; } I want to access all fields of DerivedClass2 class. I use System.Reflection and FieldInfo.GetValue() method; Bu I cant get subItem field. FieldInfo.GetValue() method return type is "object". And I cant cast to GenericClass<DerivedClass1> or I cant get DerivedClass1 type. I try this with BaseClass BaseClass instance = FieldInfo.Getvalue(this) as GenericClass<BaseClass>; but instance is null. How to get instance with type or how to get only type?

    Read the article

  • generic programming in C with void pointer.

    - by Nyan
    Hi everyone, even though it is possible to write generic code in C using void pointer(generic pointer), I find that it is quite difficult to debug the code since void pointer can take any pointer type without warning from compiler. (e.g function foo() take void pointer which is supposed to be pointer to struct, but compiler won't complain if char array is passed.) What kind of approach/strategy do you all use when using void pointer in C?

    Read the article

  • List of objects plus a tag

    - by MC
    I want to store a list of objects, lets say of type Car, but with an additional 'tag' property eg a boolean True/False which does not belong on the Car class. What is the best way to accomplish this? I need to pass the result between methods.

    Read the article

  • Can I Create A Generic Method of a Type of Interface?

    - by DaveDev
    Is it possible to create a generic method with a signature like public static string MyMethod<IMyTypeOfInterface>(object dataToPassToInterface) { // an instance of IMyTypeOfInterface knows how to handle // the data that is passed in } Would I have to instantiate the Interface with (T)Activator.CreateInstance();?

    Read the article

  • How to declare a generic constraint that is a generic type

    - by HackedByChinese
    I have a two generic abstract types: Entity and Association. Let's say Entity looks like this: public class Entity<TId> { //... } and Association looks like this: public class Association<TEntity, TEntity2> { //... } How do I constrain Association so they can be of any Entity? I can accomplish it by the following: public class Association<TEntity, TId, TEntity2, TId2> where TEntity : Entity<TId> where TEntity2: Entity<TId2> { //... } This gets very tedious as more types derive from Association, because I have to keep passing down TId and TId2. Is there a simpler way to do this, besides just removing the constraint?

    Read the article

  • How to modify TList<record> value?

    - by Astronavigator
    How to modify TList < record value ? type TTest = record a,b,c:Integer end; var List:TList<TTest>; A:TTest; P:Pointer; .... .... List[10] := A; <- OK List[10].a:=1; <- Here compiler error : Left side cannot be assined to P:=@List[10]; <- Error: Variable requied

    Read the article

  • Converting Generic Type into reference type after checking its type using GetType(). How ?

    - by Shantanu Gupta
    i am trying to call a function that is defined in a class RFIDeas_Wrapper(dll being used). But when i checked for type of reader and after that i used it to call function it shows me error Cannot convert type T to RFIDeas_Wrapper. EDIT private List<string> GetTagCollection<T>(T Reader) { TagCollection = new List<string>(); if (Reader.GetType() == typeof(RFIDeas_Wrapper)) { ((RFIDeas_Wrapper)Reader).OpenDevice(); // here Reader is of type RFIDeas_Wrapper //, but i m not able to convert Reader into its datatype. string Tag_Id = ((RFIDeas_Wrapper)Reader).TagID(); //Adds Valid Tag Ids into the collection if(Tag_Id!="0") TagCollection.Add(Tag_Id); } else if (Reader.GetType() == typeof(AlienReader)) TagCollection = ((AlienReader)Reader).TagCollection; return TagCollection; } ((RFIDeas_Wrapper)Reader).OpenDevice(); , ((AlienReader)Reader).TagCollection; I want this line to be executed without any issue. As Reader will always be of the type i m specifying. How to make compiler understand the same thing.

    Read the article

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