Search Results

Search found 78 results on 4 pages for 'covariance'.

Page 2/4 | < Previous Page | 1 2 3 4  | Next Page >

  • Why the concept of "Covariance" and "Contravariance" are applicable while implementing the methods o

    - by Amy
    The use case is some what like this: public class SomeClass: IClonable { // Some Code //Implementing interface method Public object Clone() { //Some Clonning Code } } Now my question is "Why is it not possible to use "SomeClass(As it is derivd from objec)" as a return type of Clone() method if we consider the Funda's of Covariance and Contravariance. Can somebody explain me the reason behind this implemementaion of Microsoft ????

    Read the article

  • Covariance and contravariance real world example

    - by Sir Psycho
    I'm having a little trouble understaing how I would use covariance and contravariance in the real world. So far, the only example's I've seen have been the same old array example. object[] objectArray = new string[] { "string 1", "string 2" }; It would be nice to see an example that would allow me to use it during my development if I could see it being used elsewhere. Can anyone point me to some useful resources?

    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

  • Does C# 4's covariance support nesting of generics?

    - by Scott Bilas
    I don't understand why 'x' below converts, but 'y' and 'z' do not. var list = new List<List<int>>(); IEnumerable<List<int>> x = list; List<IEnumerable<int>> y = list; IEnumerable<IEnumerable<int>> z = list; Does the new covariance feature simply not work on generics of generics or am I doing something wrong? (I'd like to avoid using .Cast< to make y and z work.)

    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

  • Is there a way to determine the Variance of an Interface / Delegate in C# 4.0?

    - by BFree
    So now that we have generic Covariance and Contravariance on interfaces and delegates in C#, I was just curious if given a Type, you can figure out the covariance/contravariance of its generic arguments. I started trying to write my own implementation, which would look through all of the methods on a given type and see if the return types and or arguments match the types in the generic arguments. The problem is that even if I have this: public interface IFoo<T> { void DoSomething(T item); } using my logic, it LOOKS like it should be contravariant, but since we didn't actually specify: public interface IFoo<in T> { void DoSomething(T item); } (the in parameter) it isn't actually contravariant. Which leads to my question: Is there a way to determine the variance of generic parameters?

    Read the article

  • Using Sub-Types And Return Types in Scala to Process a Generic Object Into a Specific One

    - by pr1001
    I think this is about covariance but I'm weak on the topic... I have a generic Event class used for things like database persistance, let's say like this: class Event( subject: Long, verb: String, directobject: Option[Long], indirectobject: Option[Long], timestamp: Long) { def getSubject = subject def getVerb = verb def getDirectObject = directobject def getIndirectObject = indirectobject def getTimestamp = timestamp } However, I have lots of different event verbs and I want to use pattern matching and such with these different event types, so I will create some corresponding case classes: trait EventCC case class Login(user: Long, timestamp: Long) extends EventCC case class Follow( follower: Long, followee: Long, timestamp: Long ) extends EventCC Now, the question is, how can I easily convert generic Events to the specific case classes. This is my first stab at it: def event2CC[T <: EventCC](event: Event): T = event.getVerb match { case "login" => Login(event.getSubject, event.getTimestamp) case "follow" => Follow( event.getSubject, event.getDirectObject.getOrElse(0), event.getTimestamp ) // ... } Unfortunately, this is wrong. <console>:11: error: type mismatch; found : Login required: T case "login" => Login(event.getSubject, event.getTimestamp) ^ <console>:12: error: type mismatch; found : Follow required: T case "follow" => Follow(event.getSubject, event.getDirectObject.getOrElse(0), event.getTimestamp) Could someone with greater type-fu than me explain if, 1) if what I want to do is possible (or reasonable, for that matter), and 2) if so, how to fix event2CC. Thanks!

    Read the article

  • Fill lower matrix with vector by row, not column

    - by mhermans
    I am trying to read in a variance-covariance matrix written out by LISREL in the following format in a plain text, whitespace separated file: 0.23675E+01 0.86752E+00 0.28675E+01 -0.36190E+00 -0.36190E+00 0.25381E+01 -0.32571E+00 -0.32571E+00 0.84425E+00 0.25598E+01 -0.37680E+00 -0.37680E+00 0.53136E+00 0.47822E+00 0.21120E+01 -0.37680E+00 -0.37680E+00 0.53136E+00 0.47822E+00 0.91200E+00 0.21120E+01 This is actually a lower diagonal matrix (including diagonal): 0.23675E+01 0.86752E+00 0.28675E+01 -0.36190E+00 -0.36190E+00 0.25381E+01 -0.32571E+00 -0.32571E+00 0.84425E+00 0.25598E+01 -0.37680E+00 -0.37680E+00 0.53136E+00 0.47822E+00 0.21120E+01 -0.37680E+00 -0.37680E+00 0.53136E+00 0.47822E+00 0.91200E+00 0.21120E+01 I can read in the values correctly with scan() or read.table(fill=T). I am however not able to correctly store the read-in vector in a matrix. The following code S <- diag(6) S[lower.tri(S,diag=T)] <- d fills the lower matrix by column, while it should fill it by row. Using matrix() does allow for the option byrow=TRUE, but this will fill in the whole matrix, not just the lower half (with diagonal). Is it possible to have both: only fill the lower matrix (with diagonal) and do it by row? (separate issue I'm having: LISREL uses 'D+01' while R only recognises 'E+01' for scientific notation. Can you change this in R to accept also 'D'?)

    Read the article

  • Matlab: Optimization by perturbing variable

    - by S_H
    My main script contains following code: %# Grid and model parameters nModel=50; nModel_want=1; nI_grid1=5; Nth=1; nRow.Scale1=5; nCol.Scale1=5; nRow.Scale2=5^2; nCol.Scale2=5^2; theta = 90; % degrees a_minor = 2; % range along minor direction a_major = 5; % range along major direction sill = var(reshape(Deff_matrix_NthModel,nCell.Scale1,1)); % variance of the coarse data matrix of size nRow.Scale1 X nCol.Scale1 %# Covariance computation % Scale 1 for ihRow = 1:nRow.Scale1 for ihCol = 1:nCol.Scale1 [cov.Scale1(ihRow,ihCol),heff.Scale1(ihRow,ihCol)] = general_CovModel(theta, ihCol, ihRow, a_minor, a_major, sill, 'Exp'); end end % Scale 2 for ihRow = 1:nRow.Scale2 for ihCol = 1:nCol.Scale2 [cov.Scale2(ihRow,ihCol),heff.Scale2(ihRow,ihCol)] = general_CovModel(theta, ihCol/(nCol.Scale2/nCol.Scale1), ihRow/(nRow.Scale2/nRow.Scale1), a_minor, a_major, sill/(nRow.Scale2*nCol.Scale2), 'Exp'); end end %# Scale-up of fine scale values by averaging [covAvg.Scale2,var_covAvg.Scale2,varNorm_covAvg.Scale2] = general_AverageProperty(nRow.Scale2/nRow.Scale1,nCol.Scale2/nCol.Scale1,1,nRow.Scale1,nCol.Scale1,1,cov.Scale2,1); I am using two functions, general_CovModel() and general_AverageProperty(), in my main script which are given as following: function [cov,h_eff] = general_CovModel(theta, hx, hy, a_minor, a_major, sill, mod_type) % mod_type should be in strings angle_rad = theta*(pi/180); % theta in degrees, angle_rad in radians R_theta = [sin(angle_rad) cos(angle_rad); -cos(angle_rad) sin(angle_rad)]; h = [hx; hy]; lambda = a_minor/a_major; D_lambda = [lambda 0; 0 1]; h_2prime = D_lambda*R_theta*h; h_eff = sqrt((h_2prime(1)^2)+(h_2prime(2)^2)); if strcmp(mod_type,'Sph')==1 || strcmp(mod_type,'sph') ==1 if h_eff<=a cov = sill - sill.*(1.5*(h_eff/a_minor)-0.5*((h_eff/a_minor)^3)); else cov = sill; end elseif strcmp(mod_type,'Exp')==1 || strcmp(mod_type,'exp') ==1 cov = sill-(sill.*(1-exp(-(3*h_eff)/a_minor))); elseif strcmp(mod_type,'Gauss')==1 || strcmp(mod_type,'gauss') ==1 cov = sill-(sill.*(1-exp(-((3*h_eff)^2/(a_minor^2))))); end and function [PropertyAvg,variance_PropertyAvg,NormVariance_PropertyAvg]=... general_AverageProperty(blocksize_row,blocksize_col,blocksize_t,... nUpscaledRow,nUpscaledCol,nUpscaledT,PropertyArray,omega) % This function computes average of a property and variance of that averaged % property using power averaging PropertyAvg=zeros(nUpscaledRow,nUpscaledCol,nUpscaledT); %# Average of property for k=1:nUpscaledT, for j=1:nUpscaledCol, for i=1:nUpscaledRow, sum=0; for a=1:blocksize_row, for b=1:blocksize_col, for c=1:blocksize_t, sum=sum+(PropertyArray((i-1)*blocksize_row+a,(j-1)*blocksize_col+b,(k-1)*blocksize_t+c).^omega); % add all the property values in 'blocksize_x','blocksize_y','blocksize_t' to one variable end end end PropertyAvg(i,j,k)=(sum/(blocksize_row*blocksize_col*blocksize_t)).^(1/omega); % take average of the summed property end end end %# Variance of averageed property variance_PropertyAvg=var(reshape(PropertyAvg,... nUpscaledRow*nUpscaledCol*nUpscaledT,1),1,1); %# Normalized variance of averageed property NormVariance_PropertyAvg=variance_PropertyAvg./(var(reshape(... PropertyArray,numel(PropertyArray),1),1,1)); Question: Using Matlab, I would like to optimize covAvg.Scale2 such that it matches closely with cov.Scale1 by perturbing/varying any (or all) of the following variables 1) a_minor 2) a_major 3) theta Thanks.

    Read the article

  • Instantiating a list of parameterized types, making beter use of Generics and Linq

    - by DanO
    I'm hashing a file with one or more hash algorithms. When I tried to parametrize which hash types I want, it got a lot messier than I was hoping. I think I'm missing a chance to make better use of generics or LINQ. I also don't like that I have to use a Type[] as the parameter instead of limiting it to a more specific set of type (HashAlgorithm descendants), I'd like to specify types as the parameter and let this method do the constructing, but maybe this would look better if I had the caller new-up instances of HashAlgorithm to pass in? public List<string> ComputeMultipleHashesOnFile(string filename, Type[] hashClassTypes) { var hashClassInstances = new List<HashAlgorithm>(); var cryptoStreams = new List<CryptoStream>(); FileStream fs = File.OpenRead(filename); Stream cryptoStream = fs; foreach (var hashClassType in hashClassTypes) { object obj = Activator.CreateInstance(hashClassType); var cs = new CryptoStream(cryptoStream, (HashAlgorithm)obj, CryptoStreamMode.Read); hashClassInstances.Add((HashAlgorithm)obj); cryptoStreams.Add(cs); cryptoStream = cs; } CryptoStream cs1 = cryptoStreams.Last(); byte[] scratch = new byte[1 << 16]; int bytesRead; do { bytesRead = cs1.Read(scratch, 0, scratch.Length); } while (bytesRead > 0); foreach (var stream in cryptoStreams) { stream.Close(); } foreach (var hashClassInstance in hashClassInstances) { Console.WriteLine("{0} hash = {1}", hashClassInstance.ToString(), HexStr(hashClassInstance.Hash).ToLower()); } }

    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

  • How is method group overload resolution different to method call overload resolution?

    - by thecoop
    The following code doesn't compile (error CS0123: No overload for 'System.Convert.ToString(object)' matches delegate 'System.Converter<T,string>'): class A<T> { void Method(T obj) { Converter<T, string> toString = Convert.ToString; } } however, this does: class A<T> { void Method(T obj) { Converter<T, string> toString = o => Convert.ToString(o); } } intellisense gives o as a T, and the Convert.ToString call as using Convert.ToString(object). In c# 3.5, delegates can be created from co/contra-variant methods, so the ToString(object) method can be used as a Converter<T, string>, as T is always guarenteed to be an object. So, the first example (method group overload resolution) should be finding the only applicable method string Convert.ToString(object o), the same as the method call overload resolution. Why is the method group & method call overload resolution producing different results?

    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

  • EF/LINQ: Where() against a property of a subtype

    - by ladenedge
    I have a set of POCOs, all of which implement the following simple interface: interface IIdObject { int Id { get; set; } } A subset of these POCOs implement this additional interface: interface IDeletableObject : IIdObject { bool IsDeleted { get; set; } } I have a repository hierarchy that looks something like this: IRepository<T <: BasicRepository<T <: ValidatingRepository<T (where T is IIdObject) I'm trying to add a FilteringRepository to the hierarchy such that all of the POCOs that implement IDeletableObject have a Where(p => p.IsDeleted == false) filter applied before any other queries take place. My goal is to avoid duplicating the hierarchy solely for IDeletableObjects. My first attempt looked like this: public override IQueryable<T> Query() { return base.Query().Where(t => ((IDeletableObject)t).IsDeleted == false); } This works well with LINQ to Objects, but when I switch to an EF backend I get: "LINQ to Entities only supports casting Entity Data Model primitive types." I went on to try some fancier parameterized solutions, but they ultimately failed because I couldn't make T covariant in the following case for some reason I don't quite understand: interface IQueryFilter<out T> // error { Expression<Func<T, bool>> GetFilter(); } I'd be happy to go into more detail on my more complicated solutions if it would help, but I think I'll stop here for now in hope that someone might have an idea for me to try. Thanks very much in advance!

    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

  • How to use a class's type as the type argument for an inherited collection property in C#

    - by Edelweiss Peimann
    I am trying to create a representation of various types of card that inherit from a generic card class and which all contain references to their owning decks. I tried re-declaring them, as suggested here, but it still won't convert to the specific card type. The code I currently have is as such: public class Deck<T> : List<T> where T : Card { void Shuffle() { throw new NotImplementedException("Shuffle not yet implemented."); } } public class Card { public Deck<Card> OwningDeck { get; set; } } public class FooCard : Card { public Deck<FooCard> OwningDeck { get { return (Deck<FooCard>)base.OwningDeck; } set { OwningDeck = value; } } } The compile-time error I am getting: Error 2 Cannot convert type 'Game.Cards.Deck' to 'Game.Cards.Deck' And a warning suggesting I use a new operator to specify that the hiding is intentional. Would doing so be a violation of convention? Is there a better way? My question to stackoverflow is this: Can what I am trying to do be done elegantly in the .NET type system? If so, can some examples be provided?

    Read the article

  • Is it possible to override a property and return a derived type in VB.NET?

    - by Casey
    Consider the following classes representing an Ordering system: Public Class OrderBase Public MustOverride Property OrderItem() as OrderItemBase End Class Public Class OrderItemBase End Class Now, suppose we want to extend these classes to a more specific set of order classes, keeping the aggregate nature of OrderBase: Public Class WebOrder Inherits OrderBase Public Overrides Property OrderItem() as WebOrderItem End Property End Class Public Class WebOrderItem Inherits OrderItemBase End Class The Overriden property in the WebOrder class will cause an error stating that the return type is different from that defined in OrderBase... however, the return type is a subclass of the type defined in OrderBase. Why won't VB allow this?

    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

  • How to specify generic method type parameters partly

    - by DNNX
    I have an extension method like below: public static T GetValueAs<T, R>(this IDictionary<string, R> dictionary, string fieldName) where T : R { R value; if (!dictionary.TryGetValue(fieldName, out value)) return default(T); return (T)value; } Currently, I can use it in the following way: var dictionary = new Dictionary<string, object(); //... var list = dictionary.GetValueAs<List<int, object("A"); // this may throw ClassCastException - this is expected behavior; It works pretty fine, but the second type parameter is really annoying. Is it possible in C# 4.0 rewrite GetValueAs is such a way that the method will still be applicable to different types of string-keyed dictionaries AND there will be no need to specify second type parameter in the calling code, i.e. use var list = dictionary.GetValueAs<List<int("A"); or at least something like var list = dictionary.GetValueAs<List<int, ?("A"); instead of var list = dictionary.GetValueAs<List<int, object("A");

    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

  • ref and out parameters in C# and cannot be marked as variant.

    - by Water Cooler v2
    What does the statement mean? From here ref and out parameters in C# and cannot be marked as variant. 1) Does it mean that the following can not be done. public class SomeClass<R, A>: IVariant<R, A> { public virtual R DoSomething( ref A args ) { return null; } } 2) Or does it mean I cannot have the following. public delegate R Reader<out R, in A>(A arg, string s); public static void AssignReadFromPeonMethodToDelegate(ref Reader<object, Peon> pReader) { pReader = ReadFromPeon; } static object ReadFromPeon(Peon p, string propertyName) { return p.GetType().GetField(propertyName).GetValue(p); } static Reader<object, Peon> pReader; static void Main(string[] args) { AssignReadFromPeonMethodToDelegate(ref pReader); bCanReadWrite = (bool)pReader(peon, "CanReadWrite"); Console.WriteLine("Press any key to quit..."); Console.ReadKey(); } I tried (2) and it worked.

    Read the article

  • How is covariance cooler than polymorphism...and not redundant?

    - by P.Brian.Mackey
    .NET 4 introduces covariance. I guess it is useful. After all, MS went through all the trouble of adding it to the C# language. But, why is Covariance more useful than good old polymorphism? I wrote this example to understand why I should implement Covariance, but I still don't get it. Please enlighten me. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Sample { class Demo { public delegate void ContraAction<in T>(T a); public interface IContainer<out T> { T GetItem(); void Do(ContraAction<T> action); } public class Container<T> : IContainer<T> { private T item; public Container(T item) { this.item = item; } public T GetItem() { return item; } public void Do(ContraAction<T> action) { action(item); } } public class Shape { public void Draw() { Console.WriteLine("Shape Drawn"); } } public class Circle:Shape { public void DrawCircle() { Console.WriteLine("Circle Drawn"); } } public static void Main() { Circle circle = new Circle(); IContainer<Shape> container = new Container<Circle>(circle); container.Do(s => s.Draw());//calls shape //Old school polymorphism...how is this not the same thing? Shape shape = new Circle(); shape.Draw(); } } }

    Read the article

< Previous Page | 1 2 3 4  | Next Page >