Search Results

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

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

  • Dynamic Linq help, different errors depending on object passed as parameter?

    - by sah302
    I have an entityDao that is inherbited by everyone of my objectDaos. I am using Dynamic Linq and trying to get some generic queries to work. I have the following code in my generic method in my EntityDao : public abstract class EntityDao<ImplementationType> where ImplementationType : Entity { public ImplementationType getOneByValueOfProperty(string getProperty, object getValue){ ImplementationType entity = null; if (getProperty != null && getValue != null) { LCFDataContext lcfdatacontext = new LCFDataContext(); //Generic LINQ Query Here entity = lcfdatacontext.GetTable<ImplementationType>().Where(getProperty + " =@0", getValue).FirstOrDefault(); //.Where(getProperty & "==" & CStr(getValue)) } //lcfdatacontext.SubmitChanges() //lcfdatacontext.Dispose() return entity; } }         Then I do the following method call in a unit test (all my objectDaos inherit entityDao): [Test] public void getOneByValueOfProperty() { Accomplishment result = accomplishmentDao.getOneByValueOfProperty("AccomplishmentType.Name", "Publication"); Assert.IsNotNull(result); } The above passes (AccomplishmentType has a relationship to accomplishment) Accomplishment result = accomplishmentDao.getOneByValueOfProperty("Description", "Can you hear me now?"); Accomplishment result = accomplishmentDao.getOneByValueOfProperty("LocalId", 4); Both of the above work Accomplishment result = accomplishmentDao.getOneByValueOfProperty("Id", New Guid("95457751-97d9-44b5-8f80-59fc2d170a4c"))       Does not work and says the following: Operator '=' incompatible with operand types 'Guid' and 'Guid Why is this happening? Guid's can't be compared? I tried == as well but same error. What's even moreso confusing is that every example of Dynamic Linq I have seen simply usings strings whether using the parameterized where predicate or this one I have commented out: //.Where(getProperty & "==" & CStr(getValue)) With or without the Cstr, many datatypes don't work with this format. I tried setting the getValue to a string instead of an object as well, but then I just get different errors (such as a multiword string would stop comparison after the first word). What am I missing to make this work with GUIDs and/or any data type? Ideally I would like to be able to just pass in a string for getValue (as I have seen for every other dynamic LINQ example) instead of the object and have it work regardless of the data Type of the column.

    Read the article

  • Can protobuf-net serialize this combination of interface and generic collection?

    - by tsupe
    I am trying to serialize a ItemTransaction and protobuf-net (r282) is having a problem. ItemTransaction : IEnumerable<KeyValuePair<Type, IItemCollection>></code> and ItemCollection is like this: FooCollection : ItemCollection<Foo> ItemCollection<T> : BindingList<T>, IItemCollection IItemCollection : IList<Item> where T is a derived type of Item. ItemCollection also has a property of type IItemCollection. I am serializing like this: IItemCollection itemCol = someService.Blah(...); ... SerializeWithLengthPrefix<IItemCollection>(stream, itemCol, PrefixStyle.Base128); My eventual goal is to serialize ItemTransaction, but am snagged with IItemCollection. Item and it's derived types can be [de]serialized with no issues, see [1], but deserializing an IItemCollection fails (serializing works). ItemCollection has a ItemExpression property and when deserializing protobuf can't create an abstract class. This makes sense to me, but I'm not sure how to get through it. ItemExpression<T> : ItemExpression, IItemExpression ItemExpression : Expression ItemExpression is abstract as is Expression How do I get this to work properly? Also, I am concerned that ItemTransaction will fail since the IItemCollections are going to be differing and unknown at compile time (an ItemTransaction will have FooCollection, BarCollection, FlimCollection, FlamCollection, etc). What am I missing (Marc) ? [1] http://stackoverflow.com/questions/2276104/protobuf-net-deserializing-across-assembly-boundaries

    Read the article

  • Comparable and Comparator contract with regards to null

    - by polygenelubricants
    Comparable contract specifies that e.compareTo(null) must throw NullPointerException. From the API: Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false. On the other hand, Comparator API mentions nothing about what needs to happen when comparing null. Consider the following attempt of a generic method that takes a Comparable, and return a Comparator for it that puts null as the minimum element. static <T extends Comparable<? super T>> Comparator<T> nullComparableComparator() { return new Comparator<T>() { @Override public int compare(T el1, T el2) { return el1 == null ? -1 : el2 == null ? +1 : el1.compareTo(el2); } }; } This allows us to do the following: List<Integer> numbers = new ArrayList<Integer>( Arrays.asList(3, 2, 1, null, null, 0) ); Comparator<Integer> numbersComp = nullComparableComparator(); Collections.sort(numbers, numbersComp); System.out.println(numbers); // "[null, null, 0, 1, 2, 3]" List<String> names = new ArrayList<String>( Arrays.asList("Bob", null, "Alice", "Carol") ); Comparator<String> namesComp = nullComparableComparator(); Collections.sort(names, namesComp); System.out.println(names); // "[null, Alice, Bob, Carol]" So the questions are: Is this an acceptable use of a Comparator, or is it violating an unwritten rule regarding comparing null and throwing NullPointerException? Is it ever a good idea to even have to sort a List containing null elements, or is that a sure sign of a design error?

    Read the article

  • How to determine if two generic type values are equal?

    - by comecme
    I'm trying to figure out how I can successfully determine if two generic type values are equal to each other. Based on Mark Byers' answer on this question I would think I can just use value.Equals() where value is a generic type. My actual problem is in a LinkedList implementation, but the problem can be shown with this simpler example. class GenericOjbect<T> { public T Value { get; private set; } public GenericOjbect(T value) { Value = value; } public bool Equals(T value) { return (Value.Equals(value)); } } Now I define an instance of GenericObject<StringBuilder> containing new StringBuilder("StackOverflow"). I would expect to get true if I call Equals(new StringBuilder("StackOverflow") on this GenericObject instance, but I get false. A sample program showing this: using System; using System.Text; class Program { static void Main() { var sb1 = new StringBuilder("StackOverflow"); var sb2 = new StringBuilder("StackOverflow"); Console.WriteLine("StringBuilder compare"); Console.WriteLine("1. == " + (sb1 == sb2)); Console.WriteLine("2. Object.Equals " + (Object.Equals(sb1, sb2))); Console.WriteLine("3. this.Equals " + (sb1.Equals(sb2))); var go1 = new GenericOjbect<StringBuilder>(sb1); var go2 = new GenericOjbect<StringBuilder>(sb2); Console.WriteLine("\nGenericObject compare"); Console.WriteLine("1. == " + (go1 == go2)); Console.WriteLine("2. Object.Equals " + (Object.Equals(go1, go2))); Console.WriteLine("3. this.Equals " + (go1.Equals(go2))); Console.WriteLine("4. Value.Equals " + (go1.Value.Equals(go2.Value))); } } For the three methods of comparing two StringBuilder objects, only the StringBuilder.Equals instance method (the third line) returns true. This is what I expected. But when comparing the GenericObject objects, its Equals() method (the third line) returns false. Interestingly enough, the fourth compare method does return true. I'd think the third and fourth comparison are actually doing the same thing. I would have expected true. Because in the Equals() method of the GenericObject class, both value and Value are of type T which in this case is a StringBuilder. Based on Mark Byers' answer in this question, I would've expected the Value.Equals() method to be using the StringBuilder's Equals() method. And as I've shown, the StringBuilder's Equal() method does return true. I've even tried public bool Equals(T value) { return EqualityComparer<T>.Default.Equals(Value, value); } but that also returns false. So, two questions here: Why doesn't the code return true? How could I implement the Equals method so it does return true?

    Read the article

  • Partial generic type inference possible in C#?

    - by Lasse V. Karlsen
    I am working on rewriting my fluent interface for my IoC class library, and when I refactored some code in order to share some common functionality through a base class, I hit upon a snag. Note: This is something I want to do, not something I have to do. If I have to make do with a different syntax, I will, but if anyone has an idea on how to make my code compile the way I want it, it would be most welcome. I want some extension methods to be available for a specific base-class, and these methods should be generic, with one generic type, related to an argument to the method, but the methods should also return a specific type related to the particular descendant they're invoked upon. Better with a code example than the above description methinks. Here's a simple and complete example of what doesn't work: using System; namespace ConsoleApplication16 { public class ParameterizedRegistrationBase { } public class ConcreteTypeRegistration : ParameterizedRegistrationBase { public void SomethingConcrete() { } } public class DelegateRegistration : ParameterizedRegistrationBase { public void SomethingDelegated() { } } public static class Extensions { public static ParameterizedRegistrationBase Parameter<T>( this ParameterizedRegistrationBase p, string name, T value) { return p; } } class Program { static void Main(string[] args) { ConcreteTypeRegistration ct = new ConcreteTypeRegistration(); ct .Parameter<int>("age", 20) .SomethingConcrete(); // <-- this is not available DelegateRegistration del = new DelegateRegistration(); del .Parameter<int>("age", 20) .SomethingDelegated(); // <-- neither is this } } } If you compile this, you'll get: 'ConsoleApplication16.ParameterizedRegistrationBase' does not contain a definition for 'SomethingConcrete' and no extension method 'SomethingConcrete'... 'ConsoleApplication16.ParameterizedRegistrationBase' does not contain a definition for 'SomethingDelegated' and no extension method 'SomethingDelegated'... What I want is for the extension method (Parameter<T>) to be able to be invoked on both ConcreteTypeRegistration and DelegateRegistration, and in both cases the return type should match the type the extension was invoked on. The problem is as follows: I would like to write: ct.Parameter<string>("name", "Lasse") ^------^ notice only one generic argument but also that Parameter<T> returns an object of the same type it was invoked on, which means: ct.Parameter<string>("name", "Lasse").SomethingConcrete(); ^ ^-------+-------^ | | +---------------------------------------------+ .SomethingConcrete comes from the object in "ct" which in this case is of type ConcreteTypeRegistration Is there any way I can trick the compiler into making this leap for me? If I add two generic type arguments to the Parameter method, type inference forces me to either provide both, or none, which means this: public static TReg Parameter<TReg, T>( this TReg p, string name, T value) where TReg : ParameterizedRegistrationBase gives me this: Using the generic method 'ConsoleApplication16.Extensions.Parameter<TReg,T>(TReg, string, T)' requires 2 type arguments Using the generic method 'ConsoleApplication16.Extensions.Parameter<TReg,T>(TReg, string, T)' requires 2 type arguments Which is just as bad. I can easily restructure the classes, or even make the methods non-extension-methods by introducing them into the hierarchy, but my question is if I can avoid having to duplicate the methods for the two descendants, and in some way declare them only once, for the base class. Let me rephrase that. Is there a way to change the classes in the first code example above, so that the syntax in the Main-method can be kept, without duplicating the methods in question? The code will have to be compatible with both C# 3.0 and 4.0. Edit: The reason I'd rather not leave both generic type arguments to inference is that for some services, I want to specify a parameter value for a constructor parameter that is of one type, but pass in a value that is a descendant. For the moment, matching of specified argument values and the correct constructor to call is done using both the name and the type of the argument. Let me give an example: ServiceContainerBuilder.Register<ISomeService>(r => r .From(f => f.ConcreteType<FileService>(ct => ct .Parameter<Stream>("source", new FileStream(...))))); ^--+---^ ^---+----^ | | | +- has to be a descendant of Stream | +- has to match constructor of FileService If I leave both to type inference, the parameter type will be FileStream, not Stream.

    Read the article

  • Binary comparison operators on generic types

    - by Brian Triplett
    I have a generic class that takes a type T. Within this class I have a method were I need to compare a type T to another type T such as: public class MyClass<T> { public T MaxValue { // Implimentation for MaxValue } public T MyMethod(T argument) { if(argument > this.MaxValue) { // Then do something } } } The comparison operation inside of MyMethod fails with Compiler Error CS0019. Is it possible to add a constraint to T to make this work? I tried adding a where T: IComparable<T> to the class definition to no avail.

    Read the article

  • Approaches for generic, compile-time safe lazy-load methods

    - by Aaronaught
    Suppose I have created a wrapper class like the following: public class Foo : IFoo { private readonly IFoo innerFoo; public Foo(IFoo innerFoo) { this.innerFoo = innerFoo; } public int? Bar { get; set; } public int? Baz { get; set; } } The idea here is that the innerFoo might wrap data-access methods or something similarly expensive, and I only want its GetBar and GetBaz methods to be invoked once. So I want to create another wrapper around it, which will save the values obtained on the first run. It's simple enough to do this, of course: int IFoo.GetBar() { if ((Bar == null) && (innerFoo != null)) Bar = innerFoo.GetBar(); return Bar ?? 0; } int IFoo.GetBaz() { if ((Baz == null) && (innerFoo != null)) Baz = innerFoo.GetBaz(); return Baz ?? 0; } But it gets pretty repetitive if I'm doing this with 10 different properties and 30 different wrappers. So I figured, hey, let's make this generic: T LazyLoad<T>(ref T prop, Func<IFoo, T> loader) { if ((prop == null) && (innerFoo != null)) prop = loader(innerFoo); return prop; } Which almost gets me where I want, but not quite, because you can't ref an auto-property (or any property at all). In other words, I can't write this: int IFoo.GetBar() { return LazyLoad(ref Bar, f => f.GetBar()); // <--- Won't compile } Instead, I'd have to change Bar to have an explicit backing field and write explicit getters and setters. Which is fine, except for the fact that I end up writing even more redundant code than I was writing in the first place. Then I considered the possibility of using expression trees: T LazyLoad<T>(Expression<Func<T>> propExpr, Func<IFoo, T> loader) { var memberExpression = propExpr.Body as MemberExpression; if (memberExpression != null) { // Use Reflection to inspect/set the property } } This plays nice with refactoring - it'll work great if I do this: return LazyLoad(f => f.Bar, f => f.GetBar()); But it's not actually safe, because someone less clever (i.e. myself in 3 days from now when I inevitably forget how this is implemented internally) could decide to write this instead: return LazyLoad(f => 3, f => f.GetBar()); Which is either going to crash or result in unexpected/undefined behaviour, depending on how defensively I write the LazyLoad method. So I don't really like this approach either, because it leads to the possibility of runtime errors which would have been prevented in the first attempt. It also relies on Reflection, which feels a little dirty here, even though this code is admittedly not performance-sensitive. Now I could also decide to go all-out and use DynamicProxy to do method interception and not have to write any code, and in fact I already do this in some applications. But this code is residing in a core library which many other assemblies depend on, and it seems horribly wrong to be introducing this kind of complexity at such a low level. Separating the interceptor-based implementation from the IFoo interface by putting it into its own assembly doesn't really help; the fact is that this very class is still going to be used all over the place, must be used, so this isn't one of those problems that could be trivially solved with a little DI magic. The last option I've already thought of would be to have a method like: T LazyLoad<T>(Func<T> getter, Action<T> setter, Func<IFoo, T> loader) { ... } This option is very "meh" as well - it avoids Reflection but is still error-prone, and it doesn't really reduce the repetition that much. It's almost as bad as having to write explicit getters and setters for each property. Maybe I'm just being incredibly nit-picky, but this application is still in its early stages, and it's going to grow substantially over time, and I really want to keep the code squeaky-clean. Bottom line: I'm at an impasse, looking for other ideas. Question: Is there any way to clean up the lazy-loading code at the top, such that the implementation will: Guarantee compile-time safety, like the ref version; Actually reduce the amount of code repetition, like the Expression version; and Not take on any significant additional dependencies? In other words, is there a way to do this just using regular C# language features and possibly a few small helper classes? Or am I just going to have to accept that there's a trade-off here and strike one of the above requirements from the list?

    Read the article

  • Concrete Implementation of Generic Form Not Working in Designer

    - by Dov
    I have a base class, defined as below (I'm also using DevExpress components): public abstract partial class BaseFormClass<R> : XtraForm where R : DataRow { ... } Contrary to what I've read from elsewhere, I'm still able to design this class. I didn't have to create a concrete class from it to do so. But, when I create a concrete class descended from it (as below), that class won't work in the designer. public partial class ConcreteFormClass : BaseFormClass<StronglyTypedRow> { ... } I get this message: The designer could not be shown for this file because none of the classes within it can be designed. The designer inspected the following classes in the file: ConcreteFormClass --- The base class 'BaseFormClass' could not be loaded. Ensure the assembly has been referenced and that all projects have been built. Has anyone seen this before? Any sort of known workaround?

    Read the article

  • c# Generic List

    - by user177883
    I m populating data for different entities into set of lists using generic lists as follows : List<Foo> foos .. List<Bar> bars .. I need to write these lists to a file, i do have a util method to get the values of properties etc. using reflection. What i want to do is: using a single method to write these into files such as: void writeToFile(a generic list) { //Which i will write to file here. } How can i do this? I want to be able to call : writeToFile(bars); writeToFile(foos);

    Read the article

  • Best Practice - Removing item from generic collection in C#

    - by Matt Davis
    I'm using C# in Visual Studio 2008 with .NET 3.5. I have a generic dictionary that maps types of events to a generic list of subscribers. A subscriber can be subscribed to more than one event. private static Dictionary<EventType, List<ISubscriber>> _subscriptions; To remove a subscriber from the subscription list, I can use either of these two options. Option 1: ISubscriber subscriber; // defined elsewhere foreach (EventType event in _subscriptions.Keys) { if (_subscriptions[event].Contains(subscriber)) { _subscriptions[event].Remove(subscriber); } } Option 2: ISubscriber subscriber; // defined elsewhere foreach (EventType event in _subscriptions.Keys) { _subscriptions[event].Remove(subscriber); } I have two questions. First, notice that Option 1 checks for existence before removing the item, while Option 2 uses a brute force removal since Remove() does not throw an exception. Of these two, which is the preferred, "best-practice" way to do this? Second, is there another, "cleaner," more elegant way to do this, perhaps with a lambda expression or using a LINQ extension? I'm still getting acclimated to these two features. Thanks. EDIT Just to clarify, I realize that the choice between Options 1 and 2 is a choice of speed (Option 2) versus maintainability (Option 1). In this particular case, I'm not necessarily trying to optimize the code, although that is certainly a worthy consideration. What I'm trying to understand is if there is a generally well-established practice for doing this. If not, which option would you use in your own code?

    Read the article

  • CreateDelegate with unknown types

    - by Giorgi
    Hello, I am trying to create Delegate for reading/writing properties of unknown type of class at runtime. I have a generic class Main<T> and a method which looks like this: Delegate.CreateDelegate(typeof(Func<T, object>), get) where get is a MethodInfo of the property that should be read. The problem is that when the property returns int (I guess this happens for value types) the above code throws ArgumentException because the method cannot be bound. In case of string it works well. To solve the problem I changed the code so that corresponding Delegate type is generated by using MakeGenericType. So now the code is: Type func = typeof(Func<,>); Type generic = func.MakeGenericType(typeof(T), get.ReturnType); var result = Delegate.CreateDelegate(generic, get) The problem now is that the created delegate instance of generic so I have to use DynamicInvoke which would be as slow as using pure reflection to read the field. So my question is why is that the first snippet of code fails with value types. According to MSDN it should work as it says that The return type of a delegate is compatible with the return type of a method if the return type of the method is more restrictive than the return type of the delegate and how to execute the delegate in the second snippet so that it is faster than reflection. Thanks.

    Read the article

  • Create method to handle multiple types of controls

    - by Praesagus
    I am trying to create a method that accepts multiple types of controls - in this case Labels and Panels. The conversion does not work because IConvertible doesn't convert these Types. Any help would be so appreciated. Thanks in advance public void LocationsLink<C>(C control) { if (control != null) { WebControl ctl = (WebControl)Convert.ChangeType(control, typeof(WebControl)); Literal txt = new Literal(); HyperLink lnk = new HyperLink(); txt.Text = "If you prefer a map to the nearest facility please "; lnk.Text = "click here"; lnk.NavigateUrl = "/content/Locations.aspx"; ctl.Controls.Add(txt); ctl.Controls.Add(lnk); } }

    Read the article

  • List<T> and IEnumerable difference

    - by Jonas Elfström
    While implementing this generic merge sort, as a kind of Code Kata, I stumbled on a difference between IEnumerable and List that I need help to figure out. Here's the MergeSort public class MergeSort<T> { public IEnumerable<T> Sort(IEnumerable<T> arr) { if (arr.Count() <= 1) return arr; int middle = arr.Count() / 2; var left = arr.Take(middle).ToList(); var right = arr.Skip(middle).ToList(); return Merge(Sort(left), Sort(right)); } private static IEnumerable<T> Merge(IEnumerable<T> left, IEnumerable<T> right) { var arrSorted = new List<T>(); while (left.Count() > 0 && right.Count() > 0) { if (Comparer<T>.Default.Compare(left.First(), right.First()) < 0) { arrSorted.Add(left.First()); left=left.Skip(1); } else { arrSorted.Add(right.First()); right=right.Skip(1); } } return arrSorted.Concat(left).Concat(right); } } If I remove the .ToList() on the left and right variables it fails to sort correctly. Do you see why? Example var ints = new List<int> { 5, 8, 2, 1, 7 }; var mergeSortInt = new MergeSort<int>(); var sortedInts = mergeSortInt.Sort(ints); With .ToList() [0]: 1 [1]: 2 [2]: 5 [3]: 7 [4]: 8 Without .ToList() [0]: 1 [1]: 2 [2]: 5 [3]: 7 [4]: 2 Edit It was my stupid test that got me. I tested it like this: var sortedInts = mergeSortInt.Sort(ints); ints.Sort(); if (Enumerable.SequenceEqual(ints, sortedInts)) Console.WriteLine("ints sorts ok"); just changing the first row to var sortedInts = mergeSortInt.Sort(ints).ToList(); removes the problem (and the lazy evaluation). EDIT 2010-12-29 I thought I would figure out just how the lazy evaluation messes things up here but I just don't get it. Remove the .ToList() in the Sort method above like this var left = arr.Take(middle); var right = arr.Skip(middle); then try this var ints = new List<int> { 5, 8, 2 }; var mergeSortInt = new MergeSort<int>(); var sortedInts = mergeSortInt.Sort(ints); ints.Sort(); if (Enumerable.SequenceEqual(ints, sortedInts)) Console.WriteLine("ints sorts ok"); When debugging You can see that before ints.Sort() a sortedInts.ToList() returns [0]: 2 [1]: 5 [2]: 8 but after ints.Sort() it returns [0]: 2 [1]: 5 [2]: 5 What is really happening here?

    Read the article

  • Can I constrain a template parameter class to implement the interfaces that are supported by other?

    - by K. Georgiev
    The name is a little blurry, so here's the situation: I'm writing code to use some 'trajectories'. The trajectories are an abstract thing, so I describe them with different interfaces. So I have a code as this: namespace Trajectories { public interface IInitial < Atom > { Atom Initial { get; set; } } public interface ICurrent < Atom > { Atom Current { get; set; } } public interface IPrevious < Atom > { Atom Previous { get; set; } } public interface ICount < Atom > { int Count { get; } } public interface IManualCount < Atom > : ICount < Atom > { int Count { get; set; } } ... } Every concrete implementation of a trajectory will implement some of the above interfaces. Here's a concrete implementation of a trajectory: public class SimpleTrajectory < Atom > : IInitial < Atom >, ICurrent < Atom >, ICount < Atom > { // ICount public int Count { get; private set; } // IInitial private Atom initial; public Atom Initial { get { return initial; } set { initial = current = value; Count = 1; } } // ICurrent private Atom current; public Atom Current { get { return current; } set { current = value; Count++; } } } Now, I want to be able to deduce things about the trajectories, so, for example I want to support predicates about different properties of some trajectory: namespace Conditions { public interface ICondition &lt Atom, Trajectory &gt { bool Test(ref Trajectory t); } public class CountLessThan &lt Atom, Trajectory &gt : ICondition &lt Atom, Trajectory &gt where Trajectory : Trajectories.ICount &lt Atom &gt { public int Value { get; set; } public CountLessThan() { } public bool Test(ref Trajectory t) { return t.Count &lt Value; } } public class CurrentNormLessThan &lt Trajectory &gt : ICondition &lt Complex, Trajectory &gt where Trajectory : Trajectories.ICurrent &lt Complex &gt { public double Value { get; set; } public CurrentNormLessThan() { } public bool Test(ref Trajectory t) { return t.Current.Norm() &lt Value; } } } Now, here's the question: What if I wanted to implement AND predicate? It would be something like this: public class And &lt Atom, CondA, TrajectoryA, CondB, TrajectoryB, Trajectory &gt : ICondition &lt Atom, Trajectory &gt where CondA : ICondition &lt Atom, TrajectoryA &gt where TrajectoryA : // Some interfaces where CondB : ICondition &lt Atom, TrajectoryB &gt where TrajectoryB : // Some interfaces where Trajectory : // MUST IMPLEMENT THE INTERFACES FOR TrajectoryA AND THE INTERFACES FOR TrajectoryB { public CondA A { get; set; } public CondB B { get; set; } public bool Test(ref Trajectory t){ return A.Test(t) && B.Test(t); } } How can I say: support only these trajectories, for which the arguments of AND are ok? So I can be able to write: var vand = new CountLessThan(32) & new CurrentNormLessThan(4.0); I think if I create an orevall interface for every subset of interfaces, I could be able to do it, but it will become quite ugly.

    Read the article

  • In VB.NET how do you specify Inherits/implements on a generic class with multi-constraints

    - by Romel Evans
    When I write the following statement in VB.Net (C# is my normal language), I get an "end of statement expected" referring to the "Implements" statement. <Serializable()> _ <XmlSchemaProvider("EtgSchema")> _ Public Class SerializeableEntity(Of T As {Class, ISerializable, New}) _ Implements IXmlSerializable, ISerializable ... End Class The C# version that I'm trying to emulate is: [Serializable] [XmlSchemaProvider("MySchema")] public class SerializableEntity<T> : IXmlSerializable, ISerializable where T : class, new() { .... } Sometimes I feel like I have 5 thumbs with VB.NET :)

    Read the article

  • Why is it impossible to declare extension methods in a generic static class?

    - by Hun1Ahpu
    I'd like to create a lot of extension methods for some generic class, e.g. for public class SimpleLinkedList<T> where T:IComparable And I've started creating methods like this: public static class LinkedListExtensions { public static T[] ToArray<T>(this SimpleLinkedList<T> simpleLinkedList) where T:IComparable { //// code } } But when I tried to make LinkedListExtensions class generic like this: public static class LinkedListExtensions<T> where T:IComparable { public static T[] ToArray(this SimpleLinkedList<T> simpleLinkedList) { ////code } } I get "Extension methods can only be declared in non-generic, non-nested static class". And I'm trying to guess where this restriction came from and have no ideas.

    Read the article

  • Covariance and Contravariance inference in C# 4.0

    - by devoured elysium
    When we define our interfaces in C# 4.0, we are allowed to mark each of the generic parameters as in or out. If we try to set a generic parameter as out and that'd lead to a problem, the compiler raises an error, not allowing us to do that. Question: If the compiler has ways of inferring what are valid uses for both covariance (out) and contravariance(in), why do we have to mark interfaces as such? Wouldn't it be enough to just let us define the interfaces as we always did, and when we tried to use them in our client code, raise an error if we tried to use them in an un-safe way? Example: interface MyInterface<out T> { T abracadabra(); } //works OK interface MyInterface2<in T> { T abracadabra(); } //compiler raises an error. //This makes me think that the compiler is cappable //of understanding what situations might generate //run-time problems and then prohibits them. Also, isn't it what Java does in the same situation? From what I recall, you just do something like IMyInterface<? extends whatever> myInterface; //covariance IMyInterface<? super whatever> myInterface2; //contravariance Or am I mixing things? Thanks

    Read the article

  • Access generic type parameter at runtime?

    - by Bart van Heukelom
    Event dispatcher interface public interface EventDispatcher { <T> EventListener<T> addEventListener(EventListener<T> l); <T> void removeEventListener(EventListener<T> l); } Implementation public class DefaultEventDispatcher implements EventDispatcher { @SuppressWarnings("unchecked") private Map<Class, Set<EventListener>> listeners = new HashMap<Class, Set<EventListener>>(); public void addSupportedEvent(Class eventType) { listeners.put(eventType, new HashSet<EventListener>()); } @Override public <T> EventListener<T> addEventListener(EventListener<T> l) { Set<EventListener> lsts = listeners.get(T); // ****** error: cannot resolve T if (lsts == null) throw new RuntimeException("Unsupported event type"); if (!lsts.add(l)) throw new RuntimeException("Listener already added"); return l; } @Override public <T> void removeEventListener(EventListener<T> l) { Set<EventListener> lsts = listeners.get(T); // ************* same error if (lsts == null) throw new RuntimeException("Unsupported event type"); if (!lsts.remove(l)) throw new RuntimeException("Listener is not here"); } } Usage EventListener<ShapeAddEvent> l = addEventListener(new EventListener<ShapeAddEvent>() { @Override public void onEvent(ShapeAddEvent event) { // TODO Auto-generated method stub } }); removeEventListener(l); I've marked two errors with a comment above (in the implementation). Is there any way to get runtime access to this information?

    Read the article

  • How to refactor these generic methods?

    - by Steve Crane
    I have written two nearly identical generic extension methods and am trying to figure out how I might refactor them into a single method. They differ only in that one operates on List and the other on List, and the properties I'm interested in are AssetID for AssetDocument and PersonID for PersonDocument. Although AssetDocument and PersonDocument have the same base class the properties are defined in each class so I don't think that helps. I have tried public static string ToCSVList<T>(this T list) where T : List<PersonDocument>, List<AssetDocument> thinking I might then be able to test the type and act accordingly but this results in the syntax error Type parameter 'T' inherits conflicting constraints These are the methods that I would like to refactor into a single method but perhaps I am simply going overboard and they would besat be left as they are. I'd like to hear what you think. public static string ToCSVList<T>(this T list) where T : List<AssetDocument> { var sb = new StringBuilder(list.Count * 36 + list.Count); string delimiter = String.Empty; foreach (var document in list) { sb.Append(delimiter + document.AssetID.ToString()); delimiter = ","; } return sb.ToString(); } public static string ToCSVList<T>(this T list) where T : List<PersonDocument> { var sb = new StringBuilder(list.Count * 36 + list.Count); string delimiter = String.Empty; foreach (var document in list) { sb.Append(delimiter + document.PersonID.ToString()); delimiter = ","; } return sb.ToString(); }

    Read the article

  • C# Get Type of IEnumerable<TModel>

    - by Jimbo
    I have a method to which I pass an IEnumerable<TModel>. Then depending on the type of TModel, the method carries out a set of instructions as below: public void MyMethod<TModel>(IEnumerable<TModel> items) where TModel : class { int operationType; switch (typeof(TModel)) { case typeof(MyModelOne): operationType = 1; break; case typeof(MyModelTwo): operationType = 2; break; case typeof(MyModelThree): operationType = 3; break; default: throw new Exception("The collection model passed to MyMethod is not recognized"); } ... } This doesnt work, I get the error: There is no application variable or memeber 'TModel'

    Read the article

  • Should I use a collection here?

    - by Eva
    So I have code set up like this: public interface IInterface { public void setField(Object field); } public abstract class AbstractClass extends JPanel implements IInterface { private Object field_; public void setField(Object field) { field_ = field; } } public class ClassA extends AbstractClass { public ClassA() { // unique ClassA constructor stuff } public Dimension getPreferredSize() { return new Dimension(1, 1); } } public class ClassB extends AbstractClass { public ClassB() { // unique ClassB constructor stuff } public Dimension getPreferredSize() { return new Dimension(42, 42); } } public class ConsumerA { public ConsumerA(Collection<AbstractClass> collection) { for (AbstractClass abstractClass : collection) { abstractClass.setField(this); abstractClass.repaint(); } } } All hunky-dory so far, until public class ConsumerB { // Option 1 public ConsumerB(ClassA a, ClassB b) { methodThatOnlyTakesA(a); methodThatOnlyTakesB(b); } // Option 2 public ConsumerB(Collection<AbstractClass> collection) { for (IInterface i : collection) { if (i instanceof ClassA) { methodThatOnlyTakesA((ClassA) i); else if (i instanceof ClassB) { methodThatOnlyTakesB((ClassB) i); } } } } public class UsingOption1 { public static void main(String[] args) { ClassA a = new ClassA(); ClassB b = new ClassB(); Collection<AbstractClass> collection = Arrays.asList(a, b); ConsumerA consumerA = new ConsumerA(collection); ConsumerB consumerB = new ConsumerB(a, b); } } public class UsingOption2 { public static void main(String[] args) { Collection<AbstractClass> collection = Arrays.asList(new ClassA(), new ClassB()); ConsumerA = new ConsumerA(collection); ConsumerB = new ConsumerB(collection); } } With a lot more classes extending AbstractClass, both options get unwieldly. Option1 would make the constructor of ConsumerB really long. Also UsingOption1 would get long too. Option2 would have way more if statements than I feel comfortable with. Is there a viable Option3? If it helps, ClassA and ClassB have all the same methods, they're just implemented differently. Thanks for slogging through my code!

    Read the article

  • Moq, a translator and an expression

    - by jeriley
    I'm working with an expression within a moq-ed "Get Service" and ran into a rather annoying issue. In order to get this test to run correctly and the get service to return what it should, there's a translator in between that takes what you've asked for, sends it off and gets what you -really- want. So, thinking this was easy I attempt this ... the fakelist is the TEntity objects (translated, used by the UI) and TEnterpriseObject is the actual persistance. mockGet.Setup(mock => mock.Get(It.IsAny<Expression<Func<TEnterpriseObject, bool>>>())).Returns( (Expression<Func<TEnterpriseObject, bool>> expression) => { var items = new List<TEnterpriseObject>(); var translator = (IEntityTranslator<TEntity, TEnterpriseObject>) ObjectFactory.GetInstance(typeof (IEntityTranslator<TEntity, TEnterpriseObject>)); fakeList.ForEach(fake => items.Add(translator.ToEnterpriseObject(fake))); items = items.Where(expression); var result = new List<TEnterpriseObject>(items); fakeList.Clear(); result.ForEach(item => translator.ToEntity(item)); return items; }); I'm getting the red squigglie under there items.where(expression) -- says it can't be infered from usage (confused between <Func<TEnterpriseObject,bool>> and <Func<TEnterpriseObject,int,bool>>) A far simpler version works great ... mockGet.Setup(mock => mock.Get(It.IsAny<Expression<Func<TEntity, bool>>>())).Returns( (Expression<Func<TEntity, bool>> expression) => fakeList.AsQueryable().Where(expression)); so I'm not sure what I'm missing... ideas?

    Read the article

  • casting Collection<SomeClass> to Collection<SomeSuperClass>

    - by skrebbel
    Hi all, I'm sure this has been answered before, but I really cannot find it. I have a java class SomeClass and an abstract class SomeSuperClass. SomeClass extends SomeSuperClass. Another abstract method has a method that returns a Collection<SomeSuperClass>. In an implementation class, I have a Collection<SomeClass> myCollection I understand that I cannot just return myCollection, because Collection<SomeClass> does not inherit from Collection<SomeSuperClass>. Nevertheless, I know that everything in myCollection is a SomeSuperClass because after all, they're SomeClass objects which extend SomeSuperClass. How can I make this work? I.e. I want public class A { private Collection<SomeClass> myCollection; public Collection<SomeSuperClass> getCollection() { return myCollection; //compile error! } } The only way I've found is casting via a non-generic type and getting unchecked warnings and whatnot. There must be a more elegant way, though? I feel that also using Collections.checkedSet() and friends are not needed, since it is statically certain that the returned collection only contains SomeClass objects (this would not be the case when downcasting instead of upcasting, but that's not what I'm doing). What am I missing? Thanks!

    Read the article

  • sOperator as and generic classes

    - by abatishchev
    I'm writing .NET On-the-Fly compiler for CLR scripting and want execution method make generic acceptable: object Execute() { return type.InvokeMember(..); } T Execute<T>() { return Execute() as T; /* doesn't work: The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint */ // also neither typeof(T) not T.GetType(), so on are possible return (T) Execute(); // ok } But I think operator as will be very useful: if result type isn't T method will return null, instead of an exception! Is it possible to do?

    Read the article

  • Generic Factorial function in C#

    - by mqpasta
    I want to write a generic function to calculate factorial in C# ... like: static T Factorial<T>(T n) { if (n <= 1) return 1; return Factorial<T>(n - 1); } but obviously having restriction that we can't perform operations on type 'T'. any alternative?

    Read the article

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