Search Results

Search found 33 results on 2 pages for 'covariant'.

Page 1/2 | 1 2  | Next Page >

  • Covariant return types in Java enums

    - by Kelvin Chung
    As mentioned in another question on this site, something like this is not legal: public enum MyEnum { FOO { public Integer doSomething() { return (Integer) super.doSomething(); } }, BAR { public String doSomething() { return (String) super.doSomething(); } }; public Object doSomething(); } This is due to covariant return types apparently not working on enum constants (again breaking the illusion that enum constants are singleton subclasses of the enum type...) So, how about we add a bit of generics: is this legal? public enum MyEnum2 { FOO { public Class<Integer> doSomething() { return Integer.class; } }, BAR { public Class<String> doSomething() { return String.class; } }; public Class<?> doSomething(); } Here, all three return Class objects, yet the individual constants are "more specific" than the enum type as a whole...

    Read the article

  • Understanding Covariant and Contravariant interfaces in C#

    - by SLC
    I've come across these in a textbook I am reading on C#, but I am having difficulty understanding them, probably due to lack of context. Is there a good concise explanation of what they are and what they are useful for out there? Edit for clarification: Covariant interface: interface IBibble<out T> . . Contravariant interface: interface IBibble<in T> . .

    Read the article

  • In C#, are event handler arguments covariant?

    - by Roger Lipscombe
    Maybe covariant's not the word, but if I have a class that raises an event, with (e.g.) FrobbingEventArgs, am I allowed to handle it with a method that takes EventArgs? Here's some code: class Program { static void Main(string[] args) { Frobber frobber = new Frobber(); frobber.Frobbing += FrobberOnFrobbing; frobber.Frob(); } private static void FrobberOnFrobbing(object sender, EventArgs e) { // Do something interesting. Note that the parameter is 'EventArgs'. } } internal class Frobber { public event EventHandler<FrobbingEventArgs> Frobbing; public event EventHandler<FrobbedEventArgs> Frobbed; public void Frob() { OnFrobbing(); // Frob. OnFrobbed(); } private void OnFrobbing() { var handler = Frobbing; if (handler != null) handler(this, new FrobbingEventArgs()); } private void OnFrobbed() { var handler = Frobbed; if (handler != null) handler(this, new FrobbedEventArgs()); } } internal class FrobbedEventArgs : EventArgs { } internal class FrobbingEventArgs : EventArgs { } The reason I ask is that ReSharper seems to have a problem with (what looks like) the equivalent in XAML, and I'm wondering if it's a bug in ReSharper, or a mistake in my understanding of C#.

    Read the article

  • Is C# 4.0 Tuple covariant

    - by RichK
    (I would check this out for myself, but I don't have VS2010 (yet)) Say I have 2 base interfaces: IBaseModelInterface IBaseViewInterface And 2 interfaces realizing those: ISubModelInterface : IBaseModelInterface ISubViewInterface : IBaseViewInterface If I define a Tuple<IBaseModelInterface, IBaseViewInterface> I would like to set that based on the result of a factory that returns Tuple<ISubModelInterface, ISubViewInterface>. In C# 3 I can't do this even though the sub interfaces realize the base interfaces. And I'm pretty sure C# 4 lets me do this if I was using IEnumerable<IBaseModelInterface> because it's now defined with the in keyword to allow covariance. So does Tuple allow me to do this? From what (little) I understand, covariance is only allowed on interfaces, so does that mean there needs to be an ITuple<T1, T2> interface? Does this exist?

    Read the article

  • .NET 4.0 Generic Invariant, Covariant, Contravariant

    - by Sameer Shariff
    Here's the scenario i am faced with: public abstract class Record { } public abstract class TableRecord : Record { } public abstract class LookupTableRecord : TableRecord { } public sealed class UserRecord : LookupTableRecord { } public interface IDataAccessLayer<TRecord> where TRecord : Record { } public interface ITableDataAccessLayer<TTableRecord> : IDataAccessLayer<TTableRecord> where TTableRecord : TableRecord { } public interface ILookupTableDataAccessLayer<TLookupTableRecord> : ITableDataAccessLayer<TLookupTableRecord> where TLookupTableRecord : LookupTableRecord { } public abstract class DataAccessLayer<TRecord> : IDataAccessLayer<TRecord> where TRecord : Record, new() { } public abstract class TableDataAccessLayer<TTableRecord> : DataAccessLayer<TTableRecord>, ITableDataAccessLayer<TTableRecord> where TTableRecord : TableRecord, new() { } public abstract class LookupTableDataAccessLayer<TLookupTableRecord> : TableDataAccessLayer<TLookupTableRecord>, ILookupTableDataAccessLayer<TLookupTableRecord> where TLookupTableRecord : LookupTableRecord, new() { } public sealed class UserDataAccessLayer : LookupTableDataAccessLayer<UserRecord> { } Now when i try to cast UserDataAccessLayer to it's generic base type ITableDataAccessLayer<TableRecord>, the compiler complains that it cannot implicitly convert the type.

    Read the article

  • C# 4.0: Covariance And Contravariance In Generics

    - by Paulo Morgado
    C# 4.0 (and .NET 4.0) introduced covariance and contravariance to generic interfaces and delegates. But what is this variance thing? According to Wikipedia, in multilinear algebra and tensor analysis, covariance and contravariance describe how the quantitative description of certain geometrical or physical entities changes when passing from one coordinate system to another.(*) But what does this have to do with C# or .NET? In type theory, a the type T is greater (>) than type S if S is a subtype (derives from) T, which means that there is a quantitative description for types in a type hierarchy. So, how does covariance and contravariance apply to C# (and .NET) generic types? In C# (and .NET), variance applies to generic type parameters and not to the resulting generic type. A generic type parameter is: covariant if the ordering of the generic types follows the ordering of the generic type parameters: Generic<T> = Generic<S> for T = S. contravariant if the ordering of the generic types is reversed from the ordering of the generic type parameters: Generic<T> = Generic<S> for T = S. invariant if neither of the above apply. If this definition is applied to arrays, we can see that arrays have always been covariant because this is valid code: object[] objectArray = new string[] { "string 1", "string 2" }; objectArray[0] = "string 3"; objectArray[1] = new object(); However, when we try to run this code, the second assignment will throw an ArrayTypeMismatchException. Although the compiler was fooled into thinking this was valid code because an object is being assigned to an element of an array of object, at run time, there is always a type check to guarantee that the runtime type of the definition of the elements of the array is greater or equal to the instance being assigned to the element. In the above example, because the runtime type of the array is array of string, the first assignment of array elements is valid because string = string and the second is invalid because string = object. This leads to the conclusion that, although arrays have always been covariant, they are not safely covariant – code that compiles is not guaranteed to run without errors. In C#, the way to define that a generic type parameter as covariant is using the out generic modifier: public interface IEnumerable<out T> { IEnumerator<T> GetEnumerator(); } public interface IEnumerator<out T> { T Current { get; } bool MoveNext(); } Notice the convenient use the pre-existing out keyword. Besides the benefit of not having to remember a new hypothetic covariant keyword, out is easier to remember because it defines that the generic type parameter can only appear in output positions — read-only properties and method return values. In a similar way, the way to define a type parameter as contravariant is using the in generic modifier: public interface IComparer<in T> { int Compare(T x, T y); } Once again, the use of the pre-existing in keyword makes it easier to remember that the generic type parameter can only be used in input positions — write-only properties and method non ref and non out parameters. Because covariance and contravariance apply only to the generic type parameters, a generic type definition can have both covariant and contravariant generic type parameters in its definition: public delegate TResult Func<in T, out TResult>(T arg); A generic type parameter that is not marked covariant (out) or contravariant (in) is invariant. All the types in the .NET Framework where variance could be applied to its generic type parameters have been modified to take advantage of this new feature. In summary, the rules for variance in C# (and .NET) are: Variance in type parameters are restricted to generic interface and generic delegate types. A generic interface or generic delegate type can have both covariant and contravariant type parameters. Variance applies only to reference types; if you specify a value type for a variant type parameter, that type parameter is invariant for the resulting constructed type. Variance does not apply to delegate combination. That is, given two delegates of types Action<Derived> and Action<Base>, you cannot combine the second delegate with the first although the result would be type safe. Variance allows the second delegate to be assigned to a variable of type Action<Derived>, but delegates can combine only if their types match exactly. If you want to learn more about variance in C# (and .NET), you can always read: Covariance and Contravariance in Generics — MSDN Library Exact rules for variance validity — Eric Lippert Events get a little overhaul in C# 4, Afterward: Effective Events — Chris Burrows Note: Because variance is a feature of .NET 4.0 and not only of C# 4.0, all this also applies to Visual Basic 10.

    Read the article

  • How to accomplish covariant return types when returning a shared_ptr?

    - by Kyle
    using namespace boost; class A {}; class B : public A {}; class X { virtual shared_ptr<A> foo(); }; class Y : public X { virtual shared_ptr<B> foo(); }; The return types aren't covariant (nor are they, therefore, legal), but they would be if I was using raw pointers instead. What's the commonly accepted idiom to work around this, if there is one?

    Read the article

  • Can I have a type that's both, covariant and contravariant, i.e. fully fungible/changeable with sub

    - by Water Cooler v2
    Just a stupid question. I could try it out in 2 minutes, really. It's just that I have 1 GB RAM and have already got 2 instances of VS 2010 open on my desktop, with an instance of VS 2005, too. Opening another instance of VS 2010 would be an over kill. Can I have a type (for now forgetting its semantics) that can be covariant as well as contravariant? For e.g. public interface Foo<in out T> { void DoFooWith(T arg); } Off to Eric Lippert's blog for the meat and potatoes of variance in C# 4.0 as there's little else anywhere that covers adequate ground on the subject.

    Read the article

  • Implement two functions with the same name but different, non-covariant return types due to multiple abstract base classes

    - by user1508167
    If I have two abstract classes defining a pure virtual function with the same name, but different, non-covariant return types, how can I derive from these and define an implementation for both their functions? #include <iostream> class ITestA { public: virtual ~ITestA() {}; virtual float test() =0; }; class ITestB { public: virtual ~ITestB() {}; virtual bool test() =0; }; class C : public ITestA, public ITestB { public: /* Somehow implement ITestA::test and ITestB::test */ }; int main() { ITestA *a = new C(); std::cout << a->test() << std::endl; // should print a float, like "3.14" ITestB *b = dynamic_cast<ITestB *>(a); if (b) { std::cout << b->test() << std::endl; // should print "1" or "0" } delete(a); return 0; } As long as I don't call C::test() directly there's nothing ambiguous, so I think that it should work somehow and I guess I just didn't find the right notation yet. Or is this impossible, if so: Why?

    Read the article

  • Covariance and Contravariance on the same type argument

    - by William Edmondson
    The C# spec states that an argument type cannot be both covariant and contravariant at the same time. This is apparent when creating a covariant or contravariant interface you decorate your type parameters with "out" or "in" respectively. There is not option that allows both at the same time ("outin"). Is this limitation simply a language specific constraint or are there deeper, more fundamental reasons based in category theory that would make you not want your type to be both covariant and contravariant? Edit: My understanding was that arrays were actually both covariant and contravariant. public class Pet{} public class Cat : Pet{} public class Siamese : Cat{} Cat[] cats = new Cat[10]; Pet[] pets = new Pet[10]; Siamese[] siameseCats = new Siamese[10]; //Cat array is covariant pets = cats; //Cat array is also contravariant since it accepts conversions from wider types cats = siameseCats;

    Read the article

  • When is C++ covariance the best solution?

    - by Neil Butterworth
    This question was asked here a few hours ago and made me realise that I have never actually used covariant return types in my own code. For those not sure what covariance is, it's allowing the return type of (typically) virtual functions to differ provided the types are part of the same inheritance hierarchy. For example: struct A { virtual ~A(); virtual A * f(); ... }; struct B : public A { virtual B * f(); ... }; The different return types of the two f() functions are said to be covariant. Older versions of C++ required the return types to be the same, so B would have to look like: struct B : public A { virtual A * f(); ... }; So, my question: Does anyone have a real-world example where covariant return types of virtual functions are required, or produce a superior solution to simply returning a base pointer or reference?

    Read the article

  • java generics covariance

    - by soocracy42
    I am having trouble understanding the following article: http://www.ibm.com/developerworks/java/library/j-jtp01255.html Under, Generics are not covariant the author states, Because ln is a List, adding a Float to it seems perfectly legal. But if ln were aliased with li, then it would break the type-safety promise implicit in the definition of li -- that it is a list of integers, which is why generic types cannot be covariant. I can't understand the part where it says "if ln were aliased with li". What does the author means by alias?(reference?). The code snippet above the quoted line seems to illustrate WHAT is illegal in java and not WHY. It would be very helpful to me if somebody could explain with an example. Thanks in advance.

    Read the article

  • Seeking Functional Programming Lexicon

    - by Randall Schulz
    Hi, Knowing the argot of a field helps me a lot, especially since it allows me to converse intelligently with those who know a lot more than I, so I would like to find a good lexicon of Functional Programming terms. E.g., I repeatedly encounter these: Functor, Arrow, Category, Kleisli, Monad, Monoid, a veritable zoo of Morphisms, etc. I also notice many of these appear with prefixes such as "covariant", "co-", "endo-" etc. Of these, I can say I actually understand Monoid and Covariant and sort of get Monad, but the rest are still gibberish to me. (Note that I don't mean this list as exhaustive and I'm not looking to have these defined or described for me here, I'm looking for learning resources.) Can someone point me towards an FP lexicon? It need not be on-line, as long as it's possible to find it (and it's not a rare volume for which I'd have to pay many tens of dollars).

    Read the article

  • With C# 3.0, how to write Interface based code with generic collection?

    - by Deecay
    I want to write code that is decouple and clean, and I know that by programming to an interface instead of the implementation, my code will be more flexible and extensible. So, instead of writing methods like: bool IsProductAvailable(ProductTypeA product); I write methods like: bool IsProductAvailable(IProduct product); As long as my products implement IProduct: class ProductTypeA : IProduct I should be OK. All is well until I start using generic collections. Since C# 3.0 doesn't support covariant and contravariant, even though both ProuctTypeA and ProductTypeB implements IProduct, you cannot put List in List. This is pretty troublesome because a lot of times I want to write something like: bool AreProductsAvailable(List<IProduct> products); So that I can check product avaialbility by writing: List<ProductA> productsArrived = GetDataFromDataabase(); bool result = AreProductsAvailable(productsArrived); And I want to write just one AreProductsAvailable() method that works with all IProduct collections. I know that C# 4.0 is going to support covariant and contravariant, but I also realize that there other libraries that seemed to have the problem solved. For instance, I was trying out ILOG Gantt the gantt chart control, and found that they have a lot of collection intefaces that looks like this: IActivityCollection ILinkCollection So it seems like their approach is wrapping the generic collection with an interface. So instead of "bool AreProductsAvailable(List products);", I can do: bool AreProductsAvailable(IProductCollection products); And then write some code so that IProductCollection takes whatever generic collection of IProduct, be it List or List. However, I don't know how to write an IProductCollection interface that does that "magic". :-< (ashame) .... Could someone shed me some light? This has been bugging me for so long, and I so wanted to do the "right thing". Well, thanks!

    Read the article

  • Generics in a bidirectional association

    - by Verhoevenv
    Let's say I have two classes A and B, with B a subtype of A. This is only part of a richer type hierarchy, obviously, but I don't think that's relevant. Assume A is the root of the hierarchy. There is a collection class C that keeps track of a list of A's. However, I want to make C generic, so that it is possible to make an instance that only keeps B's and won't accept A's. class A(val c: C[A]) { c.addEntry(this) } class B(c: C[A]) extends A(c) class C[T <: A]{ val entries = new ArrayBuffer[T]() def addEntry(e: T) { entries += e } } object Generic { def main(args : Array[String]) { val c = new C[B]() new B(c) } } The code above obviously give the error 'type mismatch: found C[B], required C[A]' on the new B(c) line. I'm not sure how this can be fixed. It's not possible to make C covariant in T (like C[+T <: A]) because the ArrayBuffer is non-variantly typed in T. It's not possible to make the constructor of B require a C[B] because C can't be covariant. Am I barking up the wrong tree here? I'm a complete Scala newbie, so any ideas and tips might be helpful. Thank you! EDIT: Basically, what I'd like to have is that the compiler accepts both val c = new C[B]() new B(c) and val c = new C[A]() new B(c) but would reject val c = new C[B]() new A(c) It's probably possible to relax the typing of the ArrayBuffer in C to be A instead of T, and thus in the addEntry method as well, if that helps.

    Read the article

  • Are CK Metrics still considered useful? Is there an open source tool to help?

    - by DeveloperDon
    Chidamber & Kemerer proposed several metrics for object oriented code. Among them, depth of inheritance tree, weighted number of methods, number of member functions, number of children, and coupling between objects. Using a base of code, they tried to correlated these metrics to the defect density and maintenance effort using covariant analysis. Are these metrics actionable in projects? Perhaps they can guide refactoring. For example weighted number of methods might show which God classes needed to be broken into more cohesive classes that address a single concern. Is there approach superseded by a better method, and is there a tool that can identify problem code, particularly in moderately large project being handed off to a new developer or team?

    Read the article

  • Subterranean IL: Generics and array covariance

    - by Simon Cooper
    Arrays in .NET are curious beasts. They are the only built-in collection types in the CLR, and SZ-arrays (single dimension, zero-indexed) have their own commands and IL syntax. One of their stranger properties is they have a kind of built-in covariance long before generic variance was added in .NET 4. However, this causes a subtle but important problem with generics. First of all, we need to briefly recap on array covariance. SZ-array covariance To demonstrate, I'll tweak the classes I introduced in my previous posts: public class IncrementableClass { public int Value; public virtual void Increment(int incrementBy) { Value += incrementBy; } } public class IncrementableClassx2 : IncrementableClass { public override void Increment(int incrementBy) { base.Increment(incrementBy); base.Increment(incrementBy); } } In the CLR, SZ-arrays of reference types are implicitly convertible to arrays of the element's supertypes, all the way up to object (note that this does not apply to value types). That is, an instance of IncrementableClassx2[] can be used wherever a IncrementableClass[] or object[] is required. When an SZ-array could be used in this fashion, a run-time type check is performed when you try to insert an object into the array to make sure you're not trying to insert an instance of IncrementableClass into an IncrementableClassx2[]. This check means that the following code will compile fine but will fail at run-time: IncrementableClass[] array = new IncrementableClassx2[1]; array[0] = new IncrementableClass(); // throws ArrayTypeMismatchException These checks are enforced by the various stelem* and ldelem* il instructions in such a way as to ensure you can't insert a IncrementableClass into a IncrementableClassx2[]. For the rest of this post, however, I'm going to concentrate on the ldelema instruction. ldelema This instruction pops the array index (int32) and array reference (O) off the stack, and pushes a pointer (&) to the corresponding array element. However, unlike the ldelem instruction, the instruction's type argument must match the run-time array type exactly. This is because, once you've got a managed pointer, you can use that pointer to both load and store values in that array element using the ldind* and stind* (load/store indirect) instructions. As the same pointer can be used for both input and output to the array, the type argument to ldelema must be invariant. At the time, this was a perfectly reasonable restriction, and maintained array type-safety within managed code. However, along came generics, and with it the constrained callvirt instruction. So, what happens when we combine array covariance and constrained callvirt? .method public static void CallIncrementArrayValue() { // IncrementableClassx2[] arr = new IncrementableClassx2[1] ldc.i4.1 newarr IncrementableClassx2 // arr[0] = new IncrementableClassx2(); dup newobj instance void IncrementableClassx2::.ctor() ldc.i4.0 stelem.ref // IncrementArrayValue<IncrementableClass>(arr, 0) // here, we're treating an IncrementableClassx2[] as IncrementableClass[] dup ldc.i4.0 call void IncrementArrayValue<class IncrementableClass>(!!0[],int32) // ... ret } .method public static void IncrementArrayValue<(IncrementableClass) T>( !!T[] arr, int32 index) { // arr[index].Increment(1) ldarg.0 ldarg.1 ldelema !!T ldc.i4.1 constrained. !!T callvirt instance void IIncrementable::Increment(int32) ret } And the result: Unhandled Exception: System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array. at IncrementArrayValue[T](T[] arr, Int32 index) at CallIncrementArrayValue() Hmm. We're instantiating the generic method as IncrementArrayValue<IncrementableClass>, but passing in an IncrementableClassx2[], hence the ldelema instruction is failing as it's expecting an IncrementableClass[]. On features and feature conflicts What we've got here is a conflict between existing behaviour (ldelema ensuring type safety on covariant arrays) and new behaviour (managed pointers to object references used for every constrained callvirt on generic type instances). And, although this is an edge case, there is no general workaround. The generic method could be hidden behind several layers of assemblies, wrappers and interfaces that make it a requirement to use array covariance when calling the generic method. Furthermore, this will only fail at runtime, whereas compile-time safety is what generics were designed for! The solution is the readonly. prefix instruction. This modifies the ldelema instruction to ignore the exact type check for arrays of reference types, and so it lets us take the address of array elements using a covariant type to the actual run-time type of the array: .method public static void IncrementArrayValue<(IncrementableClass) T>( !!T[] arr, int32 index) { // arr[index].Increment(1) ldarg.0 ldarg.1 readonly. ldelema !!T ldc.i4.1 constrained. !!T callvirt instance void IIncrementable::Increment(int32) ret } But what about type safety? In return for ignoring the type check, the resulting controlled mutability pointer can only be used in the following situations: As the object parameter to ldfld, ldflda, stfld, call and constrained callvirt instructions As the pointer parameter to ldobj or ldind* As the source parameter to cpobj In other words, the only operations allowed are those that read from the pointer; stind* and similar that alter the pointer itself are banned. This ensures that the array element we're pointing to won't be changed to anything untoward, and so type safety within the array is maintained. This is a typical example of the maxim that whenever you add a feature to a program, you have to consider how that feature interacts with every single one of the existing features. Although an edge case, the readonly. prefix instruction ensures that generics and array covariance work together and that compile-time type safety is maintained. Tune in next time for a look at the .ctor generic type constraint, and what it means.

    Read the article

  • IsNullOrEmpty generic method for Array to avoid Re-Sharper warning

    - by Michael Freidgeim
    I’ve used the following extension method in many places. public static bool IsNullOrEmpty(this Object[] myArr) { return (myArr == null || myArr.Length == 0); }Recently I’ve noticed that Resharper shows warning covariant array conversion to object[] may cause an exception for the following codeObjectsOfMyClass.IsNullOrEmpty()I’ve resolved the issue by creating generic extension method public static bool IsNullOrEmpty<T>(this T[] myArr) { return (myArr == null || myArr.Length == 0); }Related linkshttp://connect.microsoft.com/VisualStudio/feedback/details/94089/add-isnullorempty-to-array-class    public static bool IsNullOrEmpty(this System.Collections.IEnumerable source)        {            if (source == null)                return true;            else            {                return !source.GetEnumerator().MoveNext();            }        }http://stackoverflow.com/questions/8560106/isnullorempty-equivalent-for-array-c-sharp

    Read the article

  • Java language features which have no equivalent in C#

    - by jthg
    Having mostly worked with C#, I tend to think in terms of C# features which aren't available in Java. After working extensively with Java over the last year, I've started to discover Java features that I wish were in C#. Below is a list of the ones that I'm aware of. Can anyone think of other Java language features which a person with a C# background may not realize exists? The articles http://www.25hoursaday.com/CsharpVsJava.html and http://en.wikipedia.org/wiki/Comparison_of_Java_and_C_Sharp give a very extensive list of differences between Java and C#, but I wonder whether I missed anything in the (very) long articles. I can also think of one feature (covariant return type) which I didn't see mentioned in either article. Please limit answers to language or core library features which can't be effectively implemented by your own custom code or third party libraries. Covariant return type - a method can be overridden by a method which returns a more specific type. Useful when implementing an interface or extending a class and you want a method to override a base method, but return a type more specific to your class. Enums are classes - an enum is a full class in java, rather than a wrapper around a primitive like in .Net. Java allows you to define fields and methods on an enum. Anonymous inner classes - define an anonymous class which implements a method. Although most of the use cases for this in Java are covered by delegates in .Net, there are some cases in which you really need to pass multiple callbacks as a group. It would be nice to have the choice of using an anonymous inner class. Checked exceptions - I can see how this is useful in the context of common designs used with Java applications, but my experience with .Net has put me in a habit of using exceptions only for unrecoverable conditions. I.E. exceptions indicate a bug in the application and are only caught for the purpose of logging. I haven't quite come around to the idea of using exceptions for normal program flow. strictfp - Ensures strict floating point arithmetic. I'm not sure what kind of applications would find this useful. fields in interfaces - It's possible to declare fields in interfaces. I've never used this. static imports - Allows one to use the static methods of a class without qualifying it with the class name. I just realized today that this feature exists. It sounds like a nice convenience.

    Read the article

  • Covariance and Contravariance in C#

    - by edalorzo
    I will start by saying that I am Java developer learning to program in C#. As such I do comparisons of what I know with what I am learning. I have been playing with C# generics for a few hours now, and I have been able to reproduce the same things I know in Java in C#, with the exception of a couple of examples using covariance and contravariance. The book I am reading is not very good in the subject. I will certainly seek more info on the web, but while I do that, perhaps you can help me find a C# implementation for the following Java code. An example is worth a thousand words, and I was hoping that by looking a good code sample I will be able to assimilate this more rapidly. Covariance In Java I can do something like this: public static double sum(List<? extends Number> numbers) { double summation = 0.0; for(Number number : numbers){ summation += number.doubleValue(); } return summation; } I can use this code as follows: List<Integer> myInts = asList(1,2,3,4,5); List<Double> myDoubles = asList(3.14, 5.5, 78.9); List<Long> myLongs = asList(1L, 2L, 3L); double result = 0.0; result = sum(myInts); result = sum(myDoubles) result = sum(myLongs); Now I did discover that C# supports covariance/contravariance only on interfaces and as long as they have been explicitly declared to do so (out). I think I was not able to reproduce this case, because I could not find a common ancestor of all numbers, but I believe that I could have used IEnumerable to implement such thing if a common ancestor exists. Since IEnumerable is a covariant type. Right? Any thoughts on how to implement the list above? Just point me into the right direction. Is there any common ancestor of all numeric types? Contravariance The contravariance example I tried was the following. In Java I can do this to copy one list into another. public static void copy(List<? extends Number> source, List<? super Number> destiny){ for(Number number : source) { destiny.add(number); } } Then I could use it with contravariant types as follows: List<Object> anything = new ArrayList<Object>(); List<Integer> myInts = asList(1,2,3,4,5); copy(myInts, anything); My basic problem, trying to implement this in C# is that I could not find an interface that was both covariant and contravariant at the same time, as it is case of List in my example above. Maybe it can be done with two different interface in C#. Any thoughts on how to implement this? Thank you very much to everyone for any answers you can contribute. I am pretty sure I will learn a lot from any example you can provide.

    Read the article

  • C# 4.0 RC, Silverlight 4.0 RC Covariance

    - by Ant
    Hi, I am trying to develop a Silverlight 4 application using C# 4.0. I have a case like this: public class Foo<T> : IEnumerable<T> { .... } Elsewhere: public class MyBaseType : MyInterface { ... } And the usage where I am having problems: Foo<MyBaseType> aBunchOfStuff = new Foo<MyBaseType>(); Foo<MyInterface> moreGeneralStuff = myListOFStuff; Now I believe this was impossible in C# 3.0 because generic type were "Invariant". However I thought this was possible in C# 4.0 through the new covariance for generics technology? As I understand it, in C# 4.0 a lot of common interfaces (like IEnumerable) have been modified to support variance. In this case does my Foo class need to anything special in order to become covariant? And is covariance supported in Silverlight 4 (RC) ?

    Read the article

  • How to implement collection with covariance when delegating to another collection for storage?

    - by memelet
    I'm trying to implement a type of SortedMap with extended semantics. I'm trying to delegate to SortedMap as the storage but can't get around the variance constraints: class IntervalMap[A, +B](implicit val ordering: Ordering[A]) //extends ... { var underlying = SortedMap.empty[A, List[B]] } Here is the error I get. I understand why I get the error (I understand variance). What I don't get is how to implement this type of delegation. And yes, the covariance on B is required. error: covariant type B occurs in contravariant position in type scala.collection.immutable.SortedMap[A,List[B]] of parameter of setter underlying_=

    Read the article

  • Forward declaration of derived inner class

    - by Loom
    I ran into problem implementing some variations of factory method. // from IFoo.h struct IFoo { struct IBar { virtual ~IBar() = 0; virtual void someMethod() = 0; }; virtual IBar *createBar() = 0; }; // from Foo.h struct Foo : IFoo { // implementation of Foo, Bar in Foo.cpp struct Bar : IBar { virtual ~Bar(); virtual void someMethod(); }; virtual Bar *createBar(); // implemented in Foo.cpp }; I'd like to place declaration of Foo::Bar in Foo.cpp. For now I cannot succeed: struct Foo : IFoo { //struct Bar; //1. error: invalid covariant return type // for ‘virtual Foo::Bar* //struct Bar : IBar; //2. error: expected ‘{’ before ‘;’ token virtual Bar *createBar(); // virtual IBar *createBar(); // Is not acceptable by-design }; Is there a trick to have just forward declaration of Boo in Foo.hpp and to have full declaration in Foo.cpp?

    Read the article

  • .net runtime type casting when using reflection

    - by Mike
    I have need to cast a generic list of a concrete type to a generic list of an interface that the concrete types implement. This interface list is a property on an object and I am assigning the value using reflection. I only know the value at runtime. Below is a simple code example of what I am trying to accomplish: public void EmployeeTest() { IList<Employee> initialStaff = new List<Employee> { new Employee("John Smith"), new Employee("Jane Doe") }; Company testCompany = new Company("Acme Inc"); //testCompany.Staff = initialStaff; PropertyInfo staffProperty = testCompany.GetType().GetProperty("Staff"); staffProperty.SetValue(testCompany, (staffProperty.PropertyType)initialStaff, null); } Classes are defined like so: public class Company { private string _name; public string Name { get { return _name; } set { _name = value; } } private IList<IEmployee> _staff; public IList<IEmployee> Staff { get { return _staff; } set { _staff = value; } } public Company(string name) { _name = name; } } public class Employee : IEmployee { private string _name; public string Name { get { return _name; } set { _name = value; } } public Employee(string name) { _name = name; } } public interface IEmployee { string Name { get; set; } } Any thoughts? I am using .NET 4.0. Would the new covariant or contravariant features help? Thanks in advance.

    Read the article

1 2  | Next Page >