Search Results

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

Page 22/41 | < Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >

  • How to implement == or >= operators for generic type

    - by momsd
    I have a generic type Foo which has a internal generic class Boo. Boo class a property Value of type K. In a method inside Foo i want to do a boo.Value >= value Note that second operand value is of type T. while compiling i am getting following error: Operator '=' cannot be applied to operands of type 'T' and 'T' Can anyone please tell me whats the problem here?

    Read the article

  • Semi-generic function

    - by Fredrik Ullner
    I have a bunch of overloaded functions that operate on certain data types such as int, double and strings. Most of these functions perform the same action, where only a specific set of data types are allowed. That means I cannot create a simple generic template function as I lose type safety (and potentially incurring a run-time problem for validation within the function). Is it possible to create a "semi-generic compile time type safe function"? If so, how? If not, is this something that will come up in C++0x? An (non-valid) idea; template <typename T, restrict: int, std::string > void foo(T bar); ... foo((int)0); // OK foo((std::string)"foobar"); // OK foo((double)0.0); // Compile Error Note: I realize I could create a class that has overloaded constructors and assignment operators and pass a variable of that class instead to the function.

    Read the article

  • What's the best way of using a pair (triple, etc) of values as one value in C#?

    - by Yacoder
    That is, I'd like to have a tuple of values. The use case on my mind: Dictionary<Pair<string, int>, object> or Dictionary<Triple<string, int, int>, object> Are there built-in types like Pair or Triple? Or what's the best way of implementing it? Update There are some general-purpose tuples implementations described in the answers, but for tuples used as keys in dictionaries you should additionaly verify correct calculation of the hash code. Some more info on that in another question. Update 2 I guess it is also worth reminding, that when you use some value as a key in dictionary, it should be immutable.

    Read the article

  • C# BinarySearch breaks when inheriting from something that implements IComparable<T>?

    - by Ender
    In .NET the BinarySearch algorithm (in Lists, Arrays, etc.) appears to fail if the items you are trying to search inherit from an IComparable instead of implementing it directly: List<B> foo = new List<B>(); // B inherits from A, which implements IComparable<A> foo.Add(new B()); foo.BinarySearch(new B()); // InvalidOperationException, "Failed to compare two elements in the array." Where: public abstract class A : IComparable<A> { public int x; public int CompareTo(A other) { return x.CompareTo(other.x); } } public class B : A {} Is there a way around this? Implementing CompareTo(B other) in class B doesn't seem to work.

    Read the article

  • Dynamic casting using a generic interface

    - by Phil Whittaker
    Hi Is there any way to cast to a dynamic generic interface.. Site s = new Site(); IRepository<Site> obj = (IRepository<s.GetType()>)ServiceLocator.Current.GetInstance(t) obviously the above won't compile with this cast. Is there anyway to do a dynamic cast of a generic interface. I have tried adding a non generic interface but the system is looses objects in the Loc container. Thanks Phil

    Read the article

  • Nullable<T> as a parameter

    - by ferch
    I alredy have this: public static object GetDBValue(object ObjectEvaluated) { if (ObjectEvaluated == null) return DBNull.Value; else return ObjectEvaluated; } used like: List<SqlParameter> Params = new List<SqlParameter>(); Params.Add(new SqlParameter("@EntityType", GetDBValue(EntityType))); Now i wanted to keep the same interface but extend that to use it with nullable public static object GetDBValue(int? ObjectEvaluated) { if (ObjectEvaluated.HasValue) return ObjectEvaluated.Value; else return DBNull.Value; } public static object GetDBValue(DateTime? ObjectEvaluated) {...} but i want only 1 function GetDBValue for nullables. How do I do that and keep the call as is is? Is that possible at all? I can make it work like: public static object GetDBValue<T>(Nullable<T> ObjectEvaluated) where T : struct { if (ObjectEvaluated.HasValue) return ObjectEvaluated.Value; else return DBNull.Value; } But the call changes to: Params.Add(new SqlParameter("@EntityID ", GetDBValue<int>(EntityID)));

    Read the article

  • How do I create a new AnyType[] array?

    - by cb
    Which is the best practice in this situation? I would like an un-initialized array of the same type and length as the original. public static <AnyType extends Comparable<? super AnyType>> void someFunction(AnyType[] someArray) { AnyType[] anotherArray = (AnyType[]) new Comparable[someArray.length]; ...or... AnyType[] anotherArray = (AnyType[]) new Object[someArray.length]; ...some other code... } Thanks, CB

    Read the article

  • Generic Lists copying references rather than creating a copiedList

    - by Dean
    I was developing a small function when trying to run an enumerator across a list and then carry out some action. (Below is an idea of what I was trying to do. When trying to remove I got a "Collection cannot be modified" which after I had actually woken up I realised that tempList must have just been assigned myLists reference rather than a copy of myLists. After that I tried to find a way to say tempList = myList.copy However nothing seems to exist?? I ended up writing a small for loop that then just added each item from myLsit into tempList but I would have thought there would have been another mechanism (like clone??) So my question(s): is my assumption about tempList receiving a reference to myList correct How should a list be copied to another list? private myList as List (Of something) sub new() myList.add(new Something) end sub sub myCalledFunction() dim tempList as new List (Of Something) tempList = myList Using i as IEnumerator = myList.getEnumarator while i.moveNext 'if some critria is met then tempList.remove(i.current) end end using end sub

    Read the article

  • Type mismatch: cannot convert from ArrayList<Data> to MyCollection

    - by Tommy
    I've read similar questions here but I'm still a little confused. MyCollection extends ArrayList<MyClass> MyClass implements Data yet this gives me the "cannot convert from ArrayList to MyCollection" MyCollection mycollection = somehandler.getCollection(); where getCollection looks like this public ArrayList<Data> getCollection() So my assumptions are obviously wrong. How can I make this work like I would like it to

    Read the article

  • Best way to test if a generic type is a string? (c#)

    - by Rex M
    I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T). When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call default(T) on an object, it returns null. For various reasons we need to ensure that if it is not a primitive type, then we will have a default instance of the type, not null. Here is attempt 1: T createDefault() { if(typeof(T).IsValueType) { return default(T); } else { return Activator.CreateInstance<T>(); } } Problem - string is not a value type, but it does not have a parameterless constructor. So, the current solution is: T createDefault() { if(typeof(T).IsValueType || typeof(T).FullName == "System.String") { return default(T); } else { return Activator.CreateInstance<T>(); } } But this feels like a kludge. Is there a nicer way to handle the string case?

    Read the article

  • Generic Class Vb.net

    - by KoolKabin
    hi guys, I am stuck with a problem about generic classes. I am confused how I call the constructor with parameters. My interface: Public Interface IDBObject Sub [Get](ByRef DataRow As DataRow) Property UIN() As Integer End Interface My Child Class: Public Class User Implements IDBObject Public Sub [Get](ByRef DataRow As System.Data.DataRow) Implements IDBObject.Get End Sub Public Property UIN() As Integer Implements IDBObject.UIN Get End Get Set(ByVal value As Integer) End Set End Property End Class My Next Class: Public Class Users Inherits DBLayer(Of User) #Region " Standard Methods " #End Region End Class My DBObject Class: Public Class DBLayer(Of DBObject As {New, IDBObject}) Public Shared Function GetData() As List(Of DBObject) Dim QueryString As String = "SELECT * ***;" Dim Dataset As DataSet = New DataSet() Dim DataList As List(Of DBObject) = New List(Of DBObject) Try Dataset = Query(QueryString) For Each DataRow As DataRow In Dataset.Tables(0).Rows **DataList.Add(New DBObject(DataRow))** Next Catch ex As Exception DataList = Nothing End Try Return DataList End Function End Class I get error in the starred area of the DBLayer Object. What might be the possible reason? what can I do to fix it? I even want to add New(byval someval as datatype) in IDBObject interface for overloading construction. but it also gives an error? how can i do it? Adding Sub New(ByVal DataRow As DataRow) in IDBObject producess following error 'Sub New' cannot be declared in an interface. Error Produced in DBLayer Object line: DataList.Add(New DBObject(DataRow)) Msg: Arguments cannot be passed to a 'New' used on a type parameter.

    Read the article

  • MSMQ - Message Queue Abstraction and Pattern

    - by Maxim Gershkovich
    Hi All, Let me define the problem first and why a messagequeue has been chosen. I have a datalayer that will be transactional and EXTREMELY insert heavy and rather then attempt to deal with these issues when they occur I am hoping to implement my application from the ground up with this in mind. I have decided to tackle this problem by using the Microsoft Message Queue and perform inserts as time permits asynchronously. However I quickly ran into a problem. Certain inserts that I perform may need to be recalled (ie: retrieved) immediately (imagine this is for POS system and what happens if you need to recall the last transaction - one that still hasn’t been inserted). The way I decided to tackle this problem is by abstracting the MessageQueue and combining it in my data access layer thereby creating the illusion of a single set of data being returned to the user of the datalayer (I have considered the other issues that occur in such a scenario (ie: essentially dirty reads and such) and have concluded for my purposes I can control these issues). However this is where things get a little nasty... I’ve worked out how to get the messages back and such (trivial enough problem) but where I am stuck is; how do I create a generic (or at least somewhat generic) way of querying my message queue? One where I can minimize the duplication between the SQL queries and MessageQueue queries. I have considered using LINQ (but have very limited understanding of the technology) and have also attempted an implementation with Predicates which so far is pretty smelly. Are there any patterns for such a problem that I can utilize? Am I going about this the wrong way? Does anyone have an of their own ideas about how I can tackle this problem? Does anyone even understand what I am talking about? :-) Any and ALL input would be highly appreciated and seriously considered… Thanks again.

    Read the article

  • Why is TreeSet<T> an internal type in .NET?

    - by Justin Niessner
    So, I was just digging around Reflector trying to find the implementation details of HashSet (out of sheer curiosity based on the answer to another question here) and noticed the following: internal class TreeSet<T> : ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, ISerializable, IDeserializationCallback Without looking too deep into the details, it looks like a Self-Balancing Binary Search Tree. My question is, is there anybody out there with the insight as to why this class is internal? Is it simply because the other collection types use it internally and hide the complexities of a BST from the general masses...or am I way off base?

    Read the article

  • LINQ-to-SQL: Searching against a CSV

    - by Peter Bridger
    I'm using LINQtoSQL and I want to return a list of matching records for a CSV contains a list of IDs to match. The following code is my starting point, having turned a CSV string in a string array, then into a generic list (which I thought LINQ would like) - but it doesn't: Error Error 22 Operator '==' cannot be applied to operands of type 'int' and 'System.Collections.Generic.List<int>' C:\Documents and Settings\....\Search.cs 41 42 C:\...\ Code DataContext db = new DataContext(); List<int> geographyList = new List<int>( Convert.ToInt32(geography.Split(',')) ); var geographyMatches = from cg in db.ContactGeographies where cg.GeographyId == geographyList select new { cg.ContactId }; Where do I go from here?

    Read the article

  • what is the best way to have a Generic Comparer

    - by oo
    I have a lot of comparer classes where the class being compared is simply checking the name property of the object and doing a string compare. For example: public class ExerciseSorter : IComparer<Exercise> { public int Compare(Exercise x, Exercise y) { return String.Compare(x.Name, y.Name); } } public class CarSorter : IComparer<Car> { public int Compare(Car x, Car y) { return String.Compare(x.Name, y.Name); } } what is the best way to have this code generic so i dont need to write redundant code over and over again.

    Read the article

  • Is converting this ArrayList to a Generic List efficient?

    - by Greg
    The code I'm writing receives an ArrayList from unmanaged code, and this ArrayList will always contain one or more objects of type Grid_Heading_Blk. I've considered changing this ArrayList to a generic List, but I'm unsure if the conversion operation will be so expensive as to nullify the benefits of working with the generic list. Currently, I'm just running a foreach (Grid_Heading_Blk in myArrayList) operation to work with the ArrayList contents after passing the ArrayList to the class that will use it. Should I convert the ArrayList to a generic typed list? And if so, what is the most efficient way of doing so?

    Read the article

  • Generic Type Parameter constraints in C# .NET

    - by activwerx
    Consider the following Generic class: public class Custom<T> where T : string { } This produces the following error: 'string' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Is there another way to constrain which types my generic class can use? Also, can I constrain to multiple types? E.G. T can only be string, int or byte

    Read the article

  • How do I put all types implementing a certain generic interface in a dictionary?

    - by James Wenday
    Given a particular interface ITarget<T> and a particular type myType, here's how you would determine T if myType implements ITarget<T>. (This code snippet is taken from the answer to an earlier question.) foreach (var i in myType.GetInterfaces ()) if (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ITarget<>)) return i.GetGenericArguments ()[0] ; However, this only checks a single type, myType. How would I create a dictionary of all such type parameters, where the key is T and the value is myType? I think it would look something like this: var searchTarget = typeof(ITarget<>); var dict = Assembly.GetExecutingAssembly().[???] .Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == searchTarget) .[???]; What goes in the blanks?

    Read the article

  • Using a Type object to create a generic

    - by Richard Neil Ilagan
    Hello all! I'm trying to create an instance of a generic class using a Type object. Basically, I'll have a collection of objects of varying types at runtime, and since there's no way for sure to know what types they exactly will be, I'm thinking that I'll have to use Reflection. I was working on something like: Type elType = Type.GetType(obj); Type genType = typeof(GenericType<>).MakeGenericType(elType); object obj = Activator.CreateInstance(genType); Which is well and good. ^_^ The problem is, I'd like to access a method of my GenericType< instance, which I can't because it's typed as an object class. I can't find a way to cast it obj into the specific GenericType<, because that was the problem in the first place (i.e., I just can't put in something like:) ((GenericType<elType>)obj).MyMethod(); How should one go about tackling this problem? Many thanks! ^_^

    Read the article

  • Generic <T> how cast ?

    - by Kris-I
    Hi, I have a "Product" base class, some other classes "ProductBookDetail","ProductDVDDetail" inherit from this class. I use a ProductService class to make operation on these classes. But, I have to do some check depending of the type (ISBN for Book, languages for DVD). I'd like to know the best way to cast "productDetail" value, I receive in SaveOrupdate. I tried GetType() and cast with (ProductBookDetail)productDetail but that's not work. Thanks, var productDetail = new ProductDetailBook() { .... }; var service = IoC.Resolve<IProductServiceGeneric<ProductDetailBook>>(); service.SaveOrUpdate(productDetail); var productDetail = new ProductDetailDVD() { .... }; var service = IoC.Resolve<IProductServiceGeneric<ProductDetailDVD>>(); service.SaveOrUpdate(productDetail); public class ProductServiceGeneric<T> : IProductServiceGeneric<T> { private readonly ISession _session; private readonly IProductRepoGeneric<T> _repo; public ProductServiceGeneric() { _session = UnitOfWork.CurrentSession; _repo = IoC.Resolve<IProductRepoGeneric<T>>(); } public void SaveOrUpdate(T productDetail) { using (ITransaction tx = _session.BeginTransaction()) { //here i'd like ot know the type and access properties depending of the class _repo.SaveOrUpdate(productDetail); tx.Commit(); } } }

    Read the article

  • Fastest way to check a List<T> for a date

    - by fishhead
    I have a list of dates that a machine has worked on, but it doesn't include a date that machine was down. I need to create a list of days worked and not worked. I am not sure of the best way to do this. I have started by incrementing through all the days of a range and checking to see if the date is in the list by iterating through the entire list each time. I am looking for a more efficient means of finding the dates. class machineday { datetime WorkingDay; } class machinedaycollection : List<machineday> { }

    Read the article

< Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >