Search Results

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

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

  • Traversing through an arbitrary dictionary tree structure in C#

    - by Rudism
    I am trying to write a recursive C# function that will operate on generic dictionaries of the form IDictionary<string, T> where T is either another IDictionary<string, T> or a string. My first failed attempt looked something like this: public string HandleDict(IDictionary<string, string> dict){ // handle the leaf-node here } public string HandleDict<T>(IDictionary<string, IDictionary<string, T>> dict){ // loop through children foreach(string key in dict.Keys){ HandleDict(dict[key]); } } I also tried variants of HandleDict<T>(IDictionary<string, T>) where T : IDictionary<string, T> but that also doesn't quite work. I know that what I want to do could be achieved through a custom class as the parameter instead of dictionaries, and that my attempts are conceptually flawed (there's no end to the recursion in the generic function). I would still like to know if there is actually a way to do what I want here using just generic IDictionaries.

    Read the article

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

    - by nullDev
    This has been introduced in C# 4.0, but is there a way to achieve this in c# 3.5? 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.5: List<User<Base>> users = new List<User<Base>>(); users.Add(new User1()); Any ideas?

    Read the article

  • Generic Any/Attach/Add function for Entity Framework

    - by Matt Thrower
    Looking through my EF classes, they're littered with code that looks like this: if (_myContext.[EntityType].Any(d => d.RowId == dc.RowId)) { _myContext.[EntityType].Attach(dc); _myContext.Entry(dc).State = EntityState.Modified; } else { _myContext.[EntityType].Add(dc); } It's the same thing over and over, and is clearly itching to be handled by a generic function. However, I'm not sure how you'd go about handling the need for it to deal with a variety of unexpected entity types. A good example to get me started would be most appreciated.

    Read the article

  • .NET generic class instance - passing a variable data type

    - by FerretallicA
    As the title suggests, I'm tyring to pass a variable data type to a template class. Something like this: frmExample = New LookupForm(Of Models.MyClass) 'Works fine Dim SelectedType As Type = InstanceOfMyClass.GetType() 'Works fine frmExample = New LookupForm(Of SelectedType) 'Ba-bow! frmExample = New LookupForm(Of InstanceOfMyClass.GetType()) 'Ba-bow! LookupForm<Models.MyClass> frmExample; Type SelectedType = InstanceOfMyClass.GetType(); frmExample = new LookupForm<SelectedType.GetType()>(); //Ba-bow frmExample = new LookupForm<(Type)SelectedType>(); //Ba-bow I'm assuming it's something to do with the template being processed at compile time but even if I'm off the mark there, it wouldn't solve my problem anyway. I can't find any relevant information on using Reflection to instance template classes either. (How) can I create an instance of a dynamically typed repository at runtime?

    Read the article

  • C# delegate or Func for 'all methods'?

    - by Michel
    Hi, i've read something about Func's and delegates and that they can help you to pass a method as a parameter. Now i have a cachingservice, and it has this declaration: public static void AddToCache<T>(T model, double millisecs, string cacheId) where T : class public static T GetFromCache<T>(string cacheId) where T : class So in a place where i want to cache some data, i check if it exists in the cache (with GetFromCache) and if not, get the data from somewhere, and the add it to the cache (with AddToCache) Now i want to extend the AddToCache method with a parameter, which is the class+method to call to get the data Then the declaration would be like this public static void AddToCache<T>(T model, double millisecs, string cacheId, Func/Delegate methode) where T : class Then this method could check wether the cache has data or not, and if not, get the data itself via the method it got provided. Then in the calling code i could say: AddToCache<Person>(p, 10000, "Person", new PersonService().GetPersonById(1)); AddToCache<Advert>(a, 100000, "Advert", new AdvertService().GetAdverts(3)); What i want to achieve is that the 'if cache is empty get data and add to cache' logic is placed on only one place. I hope this makes sense :) Oh, by the way, the question is: is this possible?

    Read the article

  • Why is Delphi unable to infer the type for a parameter TEnumerable<T>?

    - by deepc
    Consider the following declaration of a generic utility class in Delphi 2010: TEnumerableUtils = class public class function InferenceTest<T>(Param: T): T; class function Count<T>(Enumerable: TEnumerable<T>): Integer; overload; class function Count<T>(Enumerable: TEnumerable<T>; Filter: TPredicate<T>): Integer; overload; end; Somehow the compiler type inference seems to have problems here: var I: Integer; L: TList<Integer>; begin TEnumerableUtils.InferenceTest(I); // no problem here TEnumerableUtils.Count(L); // does not compile: E2250 There is no overloaded version of 'Count' that can be called with these arguments TEnumerableUtils.Count<Integer>(L); // compiles fine end; The first call works as expected and T is correctly inferred as Integer. The second call does not work, unless I also add <Integer -- then it works, as can be seen in the third call. Am I doing something wrong or is the type inference in Delphi just not supporting this (I don't think it is a problem in Java which is why expected it to work in Delphi, too).

    Read the article

  • Constraint Validation

    - by tanuja
    I am using javax.validation.Validator and relevant classes for annotation based validation. Configuration<?> configuration = Validation.byDefaultProvider().configure(); ValidatorFactory factory = configuration.buildValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<ValidatableObject>> constraintViolations = validator.validate(o); for (ConstraintViolation<ValidatableObject> value : constraintViolations) { List< Class< ? extends ConstraintValidator< ? extends Annotation,?>>> list = value.getConstraintDescriptor().getConstraintValidatorClasses(); } I get a compilation error stating: Type mismatch: cannot convert from List< Class< ? extends ConstraintValidator< capture#4-of ?,? to List< Class< ? extends ConstraintValidator< ? extends Annotation,? What am I missing?

    Read the article

  • 'Lexical' scoping of type parameters in C#

    - by leppie
    I have 2 scenarios. This fails: class F<X> { public X X { get; set; } } error CS0102: The type 'F' already contains a definition for 'X' This works: class F<X> { class G { public X X { get; set; } } } The only logical explanation is that in the second snippet the type parameter X is out of scope, which is not true... Why should a type parameter affect my definitions in a type? IMO, for consistency, either both should work or neither should work. Any other ideas? PS: I call it 'lexical', but it probably is not not the correct term.

    Read the article

  • Cannot call action method 'System.Web.Mvc.PartialViewResult Foo[T](T)' on controller 'Controller' be

    - by MedicineMan
    Cannot call action method 'System.Web.Mvc.PartialViewResult FooT' on controller 'Controller' because the action method is a generic method <% Html.RenderAction("Foo", model = Model}); %> Is there a workaround for this limitation on ASP MVC 2? I would really prefer to use a generic. The workaround that I have come up with is to change the model type to be an object. It works, but is not preferred: public PartialViewResult Foo<T>(T model) where T : class { // do stuff }

    Read the article

  • Java. Best procedure to de-serialize a Java generic object?

    - by Jake
    What is the best procedure for storing and retrieving, using native Java serialization, generic objects like ArrayList<String>? Edit: To clarify. When I serialize an object of type ArrayList<String> I'd like to de-serialize to the same type of object. However, I know of no way to cast back to this generic object without causing warnings.

    Read the article

  • Why calling ISet<dynamic>.Contains() compiles, but throws an exception at runtime?

    - by Andrey Breslav
    Please, help me to explain the following behavior: dynamic d = 1; ISet<dynamic> s = new HashSet<dynamic>(); s.Contains(d); The code compiles with no errors/warnings, but at the last line I get the following exception: Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'System.Collections.Generic.ISet<object>' does not contain a definition for 'Contains' at CallSite.Target(Closure , CallSite , ISet`1 , Object ) at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1) at FormulaToSimulation.Program.Main(String[] args) in As far as I can tell, this is related to dynamic overload resolution, but the strange things are (1) If the type of s is HashSet<dynamic>, no exception occurs. (2) If I use a non-generic interface with a method accepting a dynamic argument, no exception occurs. Thus, it looks like this problem is related particularly with generic interfaces, but I could not find out what exactly causes the problem. Is it a bug in the compiler/typesystem, or legitimate behavior?

    Read the article

  • How to create a generic C free function .

    - by nomemory
    I have some C structures related to a 'list' data structure. They look like this. struct nmlist_element_s { void *data; struct nmlist_element_s *next; }; typedef struct nmlist_element_s nmlist_element; struct nmlist_s { void (*destructor)(void *data); int (*cmp)(const void *e1, const void *e2); unsigned int size; nmlist_element *head; nmlist_element *tail; }; typedef struct nmlist_s nmlist; This way I can have different data types being hold in "nmlist_element-data" . The "constructor" (in terms of OOP) has the following signature: nmlist *nmlist_alloc(void (*destructor)(void *data)); Where "destructor" is specific function that de-allocated "data" (being hold by the nmlist_element). If I want to have a list containing integers as data, my "destructor" would like this: void int_destructor(void *data) { free((int*)data); } Still i find it rather "unfriendly" for me to write a destructor functions for every simple primitive data type. So is there a trick to write something like this ? (for primitives): void "x"_destructor(void *data, "x") { free(("x" *)data); } PS: I am not a macro fan myself, and in my short experience regarding C, i don't use them, unless necessary.

    Read the article

  • What would be different in Java if Enum declaration didn't have the recursive part

    - by atamur
    Please see http://stackoverflow.com/questions/211143/java-enum-definition and http://stackoverflow.com/questions/3061759/why-in-java-enum-is-declared-as-enume-extends-enume for general discussion. Here I would like to learn what exactly would be broken (not typesafe anymore, or requiring additional casts etc) if Enum class was defined as public class Enum<E extends Enum> I'm using this code for testing my ideas: interface MyComparable<T> { int myCompare(T o); } class MyEnum<E extends MyEnum> implements MyComparable<E> { public int myCompare(E o) { return -1; } } class FirstEnum extends MyEnum<FirstEnum> {} class SecondEnum extends MyEnum<SecondEnum> {} With it I wasn't able to find any benefits in this exact case. PS. the fact that I'm not allowed to do class ThirdEnum extends MyEnum<SecondEnum> {} when MyEnum is defined with recursion is a) not relevant, because with real enums you are not allowed to do that just because you can't extend enum yourself b) not true - pls try it in a compiler and see that it in fact is able to compile w/o any errors PPS. I'm more and more inclined to believe that the correct answer here would be "nothing would change if you remove the recursive part" - but I just can't believe that.

    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

  • How to extend this design for a generic converter in java?

    - by Jay
    Here is a small currency converter piece of code: public enum CurrencyType { DOLLAR(1), POUND(1.2), RUPEE(.25); private CurrencyType(double factor) { this.factor = factor; } private double factor; public double getFactor() { return factor; } } public class Currency { public Currency(double value, CurrencyType type) { this.value = value; this.type = type; } private CurrencyType type; private double value; public CurrencyType getCurrencyType() { return type; } public double getCurrencyValue() { return value; } public void setCurrenctyValue(double value){ this.value = value; } } public class CurrencyConversion { public static Currency convert(Currency c1, Currency c2) throws Exception { if (c1 != null && c2 != null) { c2.setCurrenctyValue(c1.getCurrencyValue() * c1.getCurrencyType().getFactor() * c2.getCurrencyType().getFactor()); return c2; } else throw new Exception(); } } I would like to improve this code to make it work for different units of conversion, for example: kgs to pounds, miles to kms, etc etc. Something that looks like this: public class ConversionManager<T extends Convertible> { public T convert(T c1, T c2) { //return null; } } Appreciate your ideas and suggestions.

    Read the article

  • How to Work Around Limitations in Generic Type Constraints in C#?

    - by Jose
    Okay I'm looking for some input, I'm pretty sure this is not currently supported in .NET 3.5 but here goes. I want to require a generic type passed into my class to have a constructor like this: new(IDictionary<string,object>) so the class would look like this public MyClass<T> where T : new(IDictionary<string,object>) { T CreateObject(IDictionary<string,object> values) { return new T(values); } } But the compiler doesn't support this, it doesn't really know what I'm asking. Some of you might ask, why do you want to do this? Well I'm working on a pet project of an ORM so I get values from the DB and then create the object and load the values. I thought it would be cleaner to allow the object just create itself with the values I give it. As far as I can tell I have two options: 1) Use reflection(which I'm trying to avoid) to grab the PropertyInfo[] array and then use that to load the values. 2) require T to support an interface like so: public interface ILoadValues { void LoadValues(IDictionary values); } and then do this public MyClass<T> where T:new(),ILoadValues { T CreateObject(IDictionary<string,object> values) { T obj = new T(); obj.LoadValues(values); return obj; } } The problem I have with the interface I guess is philosophical, I don't really want to expose a public method for people to load the values. Using the constructor the idea was that if I had an object like this namespace DataSource.Data { public class User { protected internal User(IDictionary<string,object> values) { //Initialize } } } As long as the MyClass<T> was in the same assembly the constructor would be available. I personally think that the Type constraint in my opinion should ask (Do I have access to this constructor? I do, great!) Anyways any input is welcome.

    Read the article

  • Generic extension method returning IEnumerable<T> without using reflection

    - by roosteronacid
    Consider this snippet of code: public static class MatchCollectionExtensions { public static IEnumerable<T> AsEnumerable<T>(this MatchCollection mc) { return new T[mc.Count]; } } And this class: public class Ingredient { public String Name { get; set; } } Is there any way to magically transform a MatchCollection object to a collection of Ingredient? The use-case would look something like this: var matches = new Regex("([a-z])+,?").Matches("tomato,potato,carrot"); var ingredients = matches.AsEnumerable<Ingredient>();

    Read the article

  • How do I configure StructureMap to use a generic repository?

    - by simonjreid
    I have an interface IGenericRepository<TEntity> where TEntity : IEntity and an implementation GenericRepository<TEntity> where TEntity : Entity. I'm trying to inject a specific IGenericRepository<Section> into a class using StructureMap: ObjectFactory.Initialize(x => { x.For(typeof(IGenericRepository<>)).Use(typeof(GenericRepository<>)); }); But when I try to use ObjectFactory.GetInstance<IGenericRepository<Section>>(); I get: StructureMap Exception Code: 202 No Default Instance defined for PluginFamily System.Data.Common.DbConnection Any ideas why this is or what I'm doing wrong? Thanks in advance, Simon

    Read the article

  • Generic cast type to primitive.

    - by Nix
    Is there a way to do the below? Imagine a generic result wrapper class. Where you have a type and an associated error list. When there is no result to return to the user we will use boolean to indicate success failure. I want to create a constructor that takes in an error list, and if the list is null or count 0, AND the type is a bool/Boolean i want to set it to true.... Seemingly simple, but amazingly not possible. public class Result<T>{ private T valueObject { get;set;} private List<Error> errors{ get;set;} public Result(T valueObj, List<Error> errorList){ this.valueObject = valueObj; this.errors = errorList; } public Result(List<Error> errors) { this.valueObject = default(ReturnType); if (valueObject is Boolean) { //Wont work compile //(valueObject as Boolean) = ((errors == null) || errors.Count == 0); //Compiles but detaches reference //bool temp = ((bool)(valueObject as object)) ; //temp = ((errors == null) || errors.Count == 0); } this.errors = errors; } } } Am I missing something simple? And in general I would prefer to do it without reflection.

    Read the article

  • Access to an inner type

    - by sohum
    A colleague of mine posted a question on an internal forum which got me thinking about whether this was possible through C#. Basically, he's got an interface as follows: public interface IProvider<T> { T GetT(); } Is it possible to use something that implements that interface as a type parameter to another generic class and have access to the type T without re-specifying it? For example: public class Foo<P> where P : IProvider<T> { P p; T GetInnerT() { return p.GetT(); } } This does not compile, because the type T is not defined and hence can't be used as a parameter for IProvider. Is something like this even possible? Just curious!

    Read the article

  • How to create a complete generic TreeView like data structure

    - by Nima Rikhtegar
    I want to create a completely generic treeview like structure. some thing like this: public class TreeView<T, K, L> { public T source; public K parent; public List<L> children; } as you can see in this class source, parent and also the children, all have a different generic data type. also i want my tree view to have unlimited number of levels (not just 3). this way when i want to work with my nodes in the code, all of them are going to be strongly typed. not just objects that i need to convert them to their original type. is it possible to create this kind of structure in c#, a treeview which all of its nodes are strongly typed? thanks

    Read the article

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