Search Results

Search found 136 results on 6 pages for 'gethashcode'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • How to use Object.GetHashCode() on a type that overrides GetHashCode()

    - by Jimmy
    Hi, I have a class A that implements IEquatable<, using its fields (say, A.b and A.c) for implementing/overriding Equals() and overriding GetHashCode(), and everything works fine, 99% of the time. Class A is part of a hierarchy (class B, C) that all inherit from interface D; they can all be stored together in a dictionary Dictionary, thus it's convenient when they all carry their own default Equals()/GetHashCode(). However, while constructing A I sometime need to do some work to get the values for A.b and A.c; while that's happening, I want to store a reference to the instance that's being built. In that case, I don't want to use the default Equals()/GetHashCode() overrides provided by A. Thus, I was thinking of implementing a ReferenceEqualityComparer, that's meant to force the use of Object's Equals()/GetHashCode(): private class ReferenceEqualityComparer<T> : IEqualityComparer<T> { #region IEqualityComparer<T> Members public bool Equals(T x, T y) { return System.Object.ReferenceEquals(x, y); } public int GetHashCode(T obj) { // what goes here? I want to do something like System.Object.GetHashCode(obj); } #endregion } The question is, since A overrides Object.GetHashCode(), how can I (outside of A) call Object.GetHashCode() for an instance of A? One way of course would be for A to not implement IEquatable< and always supply an IEqualityComparer< to any dictionary that I create, but I'm hoping for a different answer. Thanks

    Read the article

  • GetHashCode on null fields?

    - by Shimmy
    How do I deal with null fields in GetHashCode function? Module Module1 Sub Main() Dim c As New Contact Dim hash = c.GetHashCode End Sub Public Class Contact : Implements IEquatable(Of Contact) Public Name As String Public Address As String Public Overloads Function Equals(ByVal other As Contact) As Boolean _ Implements System.IEquatable(Of Contact).Equals Return Name = other.Name AndAlso Address = other.Address End Function Public Overrides Function Equals(ByVal obj As Object) As Boolean If ReferenceEquals(Me, obj) Then Return True If TypeOf obj Is Contact Then Return Equals(DirectCast(obj, Contact)) Else Return False End If End Function Public Overrides Function GetHashCode() As Integer Return Name.GetHashCode Xor Address.GetHashCode End Function End Class End Module

    Read the article

  • Entity Framework 4 overwrite Equals and GetHashCode of an own class property

    - by Zhok
    Hi, I’m using Visual Studio 2010 with .NET 4 and Entity Framework 4. I’m working with POCO Classes and not the EF4 Generator. I need to overwrite the Equals() and GetHashCode() Method but that doesn’t really work. Thought it’s something everybody does but I don’t find anything about the problem Online. When I write my own Classes and Equals Method, I use Equals() of property’s, witch need to be loaded by EF to be filled. Like this: public class Item { public virtual int Id { get; set; } public virtual String Name { get; set; } public virtual List<UserItem> UserItems { get; set; } public virtual ItemType ItemType { get; set; } public override bool Equals(object obj) { Item item = obj as Item; if (obj == null) { return false; } return item.Name.Equals(this.Name) && item.ItemType.Equals(this.ItemType); } public override int GetHashCode() { return this.Name.GetHashCode() ^ this.ItemType.GetHashCode(); } } That Code doesn’t work, the problems are in Equals and GetHashCode where I try to get HashCode or Equal from “ItemType” . Every time I get a NullRefernceException if I try to get data by Linq2Entites. A dirty way to fix it, is to capture the NullReferenceException and return false (by Equals) and return base.GetHashCode() (by GethashCode) but I hope there is a better way to fix this problem. I’ve wrote a little test project, with SQL Script for the DB and POCO Domain, EDMX File and Console Test Main Method. You can download it here: Download

    Read the article

  • Problem with custom Equality and GetHashCode in a mutable object

    - by Shimmy
    Hello! I am using Entity Framework in my application. I implemented with the partial class of an entity the IEquatable<T> interface: Partial Class Address : Implements IEquatable(Of Address) 'Other part generated Public Overloads Function Equals(ByVal other As Address) As Boolean _ Implements System.IEquatable(Of Address).Equals If ReferenceEquals(Me, other) Then Return True Return AddressId = other.AddressId End Function Public Overrides Function Equals(ByVal obj As Object) As Boolean If obj Is Nothing Then Return MyBase.Equals(obj) If TypeOf obj Is Address Then Return Equals(DirectCast(obj, Address)) Else Return False End Function Public Overrides Function GetHashCode() As Integer Return AddressId.GetHashCode End Function End Class Now in my code I use it this way: Sub Main() Using e As New CompleteKitchenEntities Dim job = e.Job.FirstOrDefault Dim address As New Address() job.Addresses.Add(address) Dim contains1 = job.Addresses.Contains(address) 'True e.SaveChanges() Dim contains2 = job.Addresses.Contains(address) 'False 'The problem is that I can't remove it: Dim removed = job.Addresses.Remoeve(address) 'False End Using End Sub Note (I checked in the debugger visualizer) that the EntityCollection class stores its entities in HashSet so it has to do with the GetHashCode function, I want it to depend on the ID so entities are compared by their IDs. The problem is that when I hit save, the ID changes from 0 to its db value. So the question is how can I have an equatable object, being properly hashed. Please help me find what's wrong in the GetHashCode function (by ID) and what can I change to make it work. Thanks a lot.

    Read the article

  • C# - How to override GetHashCode with Lists in object

    - by Christian
    Hi, I am trying to create a "KeySet" to modify UIElement behaviour. The idea is to create a special function if, eg. the user clicks on an element while holding a. Or ctrl+a. My approach so far, first lets create a container for all possible modifiers. If I would simply allow a single key, it would be no problem. I could use a simple Dictionary, with Dictionary<Keys, Action> _specialActionList If the dictionary is empty, use the default action. If there are entries, check what action to use depending on current pressed keys And if I wasn't greedy, that would be it... Now of course, I want more. I want to allow multiple keys or modifiers. So I created a wrapper class, wich can be used as Key to my dictionary. There is an obvious problem when using a more complex class. Currently two different instances would create two different key, and thereby he would never find my function (see code to understand, really obvious) Now I checked this post: http://stackoverflow.com/questions/638761/c-gethashcode-override-of-object-containing-generic-array which helped a little. But my question is, is my basic design for the class ok. Should I use a hashset to store the modifier and normal keyboardkeys (instead of Lists). And If so, how would the GetHashCode function look like? I know, its a lot of code to write (boring hash functions), some tips would be sufficient to get me started. Will post tryouts here... And here comes the code so far, the Test obviously fails... public class KeyModifierSet { private readonly List<Key> _keys = new List<Key>(); private readonly List<ModifierKeys> _modifierKeys = new List<ModifierKeys>(); private static readonly Dictionary<KeyModifierSet, Action> _testDict = new Dictionary<KeyModifierSet, Action>(); public static void Test() { _testDict.Add(new KeyModifierSet(Key.A), () => Debug.WriteLine("nothing")); if (!_testDict.ContainsKey(new KeyModifierSet(Key.A))) throw new Exception("Not done yet, help :-)"); } public KeyModifierSet(IEnumerable<Key> keys, IEnumerable<ModifierKeys> modifierKeys) { foreach (var key in keys) _keys.Add(key); foreach (var key in modifierKeys) _modifierKeys.Add(key); } public KeyModifierSet(Key key, ModifierKeys modifierKey) { _keys.Add(key); _modifierKeys.Add(modifierKey); } public KeyModifierSet(Key key) { _keys.Add(key); } }

    Read the article

  • Using a subset of GetHashCode() to increase AzureTable performance through partitioning

    - by makerofthings7
    Generally speaking, Azure Table IO performance improves as more partitions are used (with some tradeoffs in continuation tokens and batch updates I won't go into). Since the partition key is always a string I am considering using a "natural" load balancing technique based on a subset of the GetHashCode() of the partition key, and appending this subset to the partition key itself. This will allow all direct PK/RK queries to be computed with little overhead and with ease. Batch updates may just need an intermediate to group similar PKs together prior to submission. Question: Should I use GetHashCode() to compute the partition key? Is a better function available? If I use GetHashCode() does it matter which character I use for my PK? Is there an abstraction for Azure Table and Blob storage that does this for me already?

    Read the article

  • Why does C# not implement GetHashCode for Collections?

    - by Peterdk
    I am porting something from Java to C#. In Java the hashcode of a ArrayList depends on the items in it. In C# I always get the same hashcode from a List... Why is this? For some of my objects the hashcode needs to be different because the objects in their list property make the objects non-equal. I would expect that a hashcode is always unique for the object's state and only equals another hashcode when the object is equal. Am I wrong?

    Read the article

  • What is the best way to implement this composite GetHashCode()

    - by Frank Krueger
    I have a simple class: public class TileName { int Zoom, X, Y; public override bool Equals (object obj) { var o = obj as TileName; return (o != null) && (o.Zoom == Zoom) && (o.X == X) && (o.Y == Y); } public override int GetHashCode () { return (Zoom + X + Y).GetHashCode(); } } I was curious if I would get a better distribution of hash codes if I instead did something like: public override int GetHashCode () { return Zoom.GetHashCode() + X.GetHashCode() + Y.GetHashCode(); } This class is going to be used as a Dictionary key, so I do want to make sure there is a decent distribution.

    Read the article

  • Verification GetHashCode and Equals

    - by nettguy
    Does the following code show the correct implementation of overriding GetHashCode ? public class Person { public string fName{get;set;} public string lName { get; set; } public int age { get; set; } public override bool Equals(object obj) { Person p = obj as Person; if (p == null) return false; return ( p.GetType()==this.GetType() && p.fName==this.fName &&p.lName==this.lName && p.age==this.age ); } //I took the below code from Marc Gravell's post,I am not sure whether i have implemented it properly public override int GetHashCode() { unchecked { int hash = 13; hash = (hash * 7) + fName.GetHashCode(); hash = (hash * 7) + lName.GetHashCode(); hash = (hash * 7) + age.GetHashCode(); return hash; } } }

    Read the article

  • General advice and guidelines on how to properly override object.GetHashCode()

    - by Svish
    According to MSDN, a hash function must have the following properties: If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values. The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again. For the best performance, a hash function must generate a random distribution for all input. I keep finding myself in the following scenario: I have created a class, implemented IEquatable<T> and overridden object.Equals(object). MSDN states that: Types that override Equals must also override GetHashCode ; otherwise, Hashtable might not work correctly. And then it usually stops up a bit for me. Because, how do you properly override object.GetHashCode()? Never really know where to start, and it seems to be a lot of pitfalls. Here at StackOverflow, there are quite a few questions related to GetHashCode overriding, but most of them seems to be on quite particular cases and specific issues. So, therefore I would like to get a good compilation here. An overview with general advice and guidelines. What to do, what not to do, common pitfalls, where to start, etc. I would like it to be especially directed at C#, but I would think it will work kind of the same way for other .NET languages as well(?). I think maybe the best way is to create one answer per topic with a quick and short answer first (close to one-liner if at all possible), then maybe some more information and end with related questions, discussions, blog posts, etc., if there are any. I can then create one post as the accepted answer (to get it on top) with just a "table of contents". Try to keep it short and concise. And don't just link to other questions and blog posts. Try to take the essence of them and then rather link to source (especially since the source could disappear. Also, please try to edit and improve answers instead of created lots of very similar ones. I am not a very good technical writer, but I will at least try to format answers so they look alike, create the table of contents, etc. I will also try to search up some of the related questions here at SO that answers parts of these and maybe pull out the essence of the ones I can manage. But since I am not very stable on this topic, I will try to stay away for the most part :p

    Read the article

  • Dictionary keys don't contain a key that's already contained in keys

    - by ran
    Why is the following 'exist' boolean variable getting a value of false??? foreach (Cell existCell in this.decoratorByCell.Keys) { //this call yield the same hashcode for both cells. still exist==false bool exist = this.decoratorByCell.ContainsKey(existCell); } I've overridden GetHashCode() & Equals() Methods as follows: public override int GetHashCode() { string nodePath = GetNodePath(); return nodePath.GetHashCode() + m_ownerColumn.GetHashCode(); } public bool Equals(Cell other) { bool nodesEqual = (other.OwnerNode == null && this.OwnerNode == null) || (other.GetNodePath() == this.GetNodePath()); bool columnsEqual = (other.OwnerColumn == null && this.OwnerColumn == null) || (other.OwnerColumn == this.OwnerColumn); bool treesEqual = (this.m_ownerTree == other.m_ownerTree); return (nodesEqual && columnsEqual && treesEqual); }

    Read the article

  • Why might a System.String object not cache its hash code?

    - by Dan Tao
    A glance at the source code for string.GetHashCode using Reflector reveals the following (for mscorlib.dll version 4.0): public override unsafe int GetHashCode() { fixed (char* str = ((char*) this)) { char* chPtr = str; int num = 0x15051505; int num2 = num; int* numPtr = (int*) chPtr; for (int i = this.Length; i > 0; i -= 4) { num = (((num << 5) + num) + (num >> 0x1b)) ^ numPtr[0]; if (i <= 2) { break; } num2 = (((num2 << 5) + num2) + (num2 >> 0x1b)) ^ numPtr[1]; numPtr += 2; } return (num + (num2 * 0x5d588b65)); } } Now, I realize that the implementation of GetHashCode is not specified and is implementation-dependent, so the question "is GetHashCode implemented in the form of X or Y?" is not really answerable. I'm just curious about a few things: If Reflector has disassembled the DLL correctly and this is the implementation of GetHashCode (in my environment), am I correct in interpreting this code to indicate that a string object, based on this particular implementation, would not cache its hash code? Assuming the answer is yes, why would this be? It seems to me that the memory cost would be minimal (one more 32-bit integer, a drop in the pond compared to the size of the string itself) whereas the savings would be significant, especially in cases where, e.g., strings are used as keys in a hashtable-based collection like a Dictionary<string, [...]>. And since the string class is immutable, it isn't like the value returned by GetHashCode will ever even change. What could I be missing? UPDATE: In response to Andras Zoltan's closing remark: There's also the point made in Tim's answer(+1 there). If he's right, and I think he is, then there's no guarantee that a string is actually immutable after construction, therefore to cache the result would be wrong. Whoa, whoa there! This is an interesting point to make (and yes it's very true), but I really doubt that this was taken into consideration in the implementation of GetHashCode. The statement "therefore to cache the result would be wrong" implies to me that the framework's attitude regarding strings is "Well, they're supposed to be immutable, but really if developers want to get sneaky they're mutable so we'll treat them as such." This is definitely not how the framework views strings. It fully relies on their immutability in so many ways (interning of string literals, assignment of all zero-length strings to string.Empty, etc.) that, basically, if you mutate a string, you're writing code whose behavior is entirely undefined and unpredictable. I guess my point is that for the author(s) of this implementation to worry, "What if this string instance is modified between calls, even though the class as it is publicly exposed is immutable?" would be like for someone planning a casual outdoor BBQ to think to him-/herself, "What if someone brings an atomic bomb to the party?" Look, if someone brings an atom bomb, party's over.

    Read the article

  • Implementing GetHashCode

    - by dotnetdev
    Hi, What constitutes a good implementation of the GetHashCode method? I did some googling, and found some goodlines (MSDN) but it seems like the logic just manipulates two numbers stored as fields in the class. Is the actual logic this simple to implement this method?

    Read the article

  • Problem with custom Equality in Entity Framework

    - by Shimmy
    Hello! I am using Entity Framework in my application. I implemented with the partial class of an entity the IEquatable<T> interface: Partial Class Address : Implements IEquatable(Of Address) 'Other part generated Public Overloads Function Equals(ByVal other As Address) As Boolean _ Implements System.IEquatable(Of Address).Equals If ReferenceEquals(Me, other) Then Return True Return AddressId = other.AddressId End Function Public Overrides Function Equals(ByVal obj As Object) As Boolean If obj Is Nothing Then Return MyBase.Equals(obj) If TypeOf obj Is Address Then Return Equals(DirectCast(obj, Address)) Else Return False End Function Public Overrides Function GetHashCode() As Integer Return AddressId.GetHashCode End Function End Class Now in my code I use it this way: Sub Main() Using e As New CompleteKitchenEntities Dim job = e.Job.FirstOrDefault Dim address As New Address() job.Addresses.Add(address) Dim contains1 = job.Addresses.Contains(address) 'True e.SaveChanges() Dim contains2 = job.Addresses.Contains(address) 'False 'The problem is that I can't remove it: Dim removed = job.Addresses.Remoeve(address) 'False End Using End Sub Note (I checked in the debugger visualizer) that the EntityCollection class stores its entities in HashSet so it has to do with the GetHashCode function, I want it to depend on the ID so entities are compared by their IDs. Please help me find what's wrong in the GetHashCode function (by ID) and what can I change to make it work. Thanks a lot.

    Read the article

  • How to implement IEquatable<T> when mutable fields are part of the equality - Problem with GetHashCo

    - by Shimmy
    Hello! I am using Entity Framework in my application. I implemented with the partial class of an entity the IEquatable<T> interface: Partial Class Address : Implements IEquatable(Of Address) 'Other part generated Public Overloads Function Equals(ByVal other As Address) As Boolean _ Implements System.IEquatable(Of Address).Equals If ReferenceEquals(Me, other) Then Return True Return AddressId = other.AddressId End Function Public Overrides Function Equals(ByVal obj As Object) As Boolean If obj Is Nothing Then Return MyBase.Equals(obj) If TypeOf obj Is Address Then Return Equals(DirectCast(obj, Address)) Else Return False End Function Public Overrides Function GetHashCode() As Integer Return AddressId.GetHashCode End Function End Class Now in my code I use it this way: Sub Main() Using e As New CompleteKitchenEntities Dim job = e.Job.FirstOrDefault Dim address As New Address() job.Addresses.Add(address) Dim contains1 = job.Addresses.Contains(address) 'True e.SaveChanges() Dim contains2 = job.Addresses.Contains(address) 'False 'The problem is that I can't remove it: Dim removed = job.Addresses.Remoeve(address) 'False End Using End Sub Note (I checked in the debugger visualizer) that the EntityCollection class stores its entities in HashSet so it has to do with the GetHashCode function, I want it to depend on the ID so entities are compared by their IDs. The problem is that when I hit save, the ID changes from 0 to its db value. So the question is how can I have an equatable object, being properly hashed. Please help me find what's wrong in the GetHashCode function (by ID) and what can I change to make it work. Thanks a lot.

    Read the article

  • C# how to calculate hashcode from an object reference.

    - by Wayne
    Folks, here's a thorny problem for you! A part of the TickZoom system must collect instances of every type of object into a Dictionary< type. It is imperative that their equality and hash code be based on the instance of the object which means reference equality instead of value equality. The challenge is that some of the objects in the system have overridden Equals() and GetHashCode() for use as value equality and their internal values will change over time. That means that their Equals and GetHashCode are useless. How to solve this generically rather than intrusively? So far, We created a struct to wrap each object called ObjectHandle for hashing into the Dictionary. As you see below we implemented Equals() but the problem of how to calculate a hash code remains. public struct ObjectHandle : IEquatable<ObjectHandle>{ public object Object; public bool Equals(ObjectHandle other) { return object.ReferenceEquals(this.Object,other.Object); } } See? There is the method object.ReferenceEquals() which will compare reference equality without regard for any overridden Equals() implementation in the object. Now, how to calculate a matching GetHashCode() by only considering the reference without concern for any overridden GetHashCode() method? Ahh, I hope this give you an interesting puzzle. We're stuck over here. Sincerely, Wayne

    Read the article

  • GetHashCode Method reliability in Silverlight/WP7.1

    - by abhinav
    I am attempting to hash and keep(the hash) an object of type IEnumerable<anotherobject> which has about a 1000 entries. I'll be generating another such object, but this time I'd like to check for any changes in the values of the entries using the hash codes of the two objects. Basically, I was wondering if GetHashCode() is apt for this, both from a performance perspective and reliability perspective (getting different values for different object values and same values for same object values, always). If I have to override it, what would be a good way to do so, does it always depend on the type of anotherobject and what Equals means when comparing two anotherobjects? Is there a generic way to do it? This concern is because my object can be quite big.

    Read the article

  • Overriding GetHashCode in a mutable struct - What NOT to do?

    - by Kyle Baran
    I am using the XNA Framework to make a learning project. It has a Point struct which exposes an X and Y value; for the purpose of optimization, it breaks the rules for proper struct design, since its a mutable struct. As Marc Gravell, John Skeet, and Eric Lippert point out in their respective posts about GetHashCode() (which Point overrides), this is a rather bad thing, since if an object's values change while its contained in a hashmap (ie, LINQ queries), it can become "lost". However, I am making my own Point3D struct, following the design of Point as a guideline. Thus, it too is a mutable struct which overrides GetHashCode(). The only difference is that mine exposes and int for X, Y, and Z values, but is fundamentally the same. The signatures are below: public struct Point3D : IEquatable<Point3D> { public int X; public int Y; public int Z; public static bool operator !=(Point3D a, Point3D b) { } public static bool operator ==(Point3D a, Point3D b) { } public Point3D Zero { get; } public override int GetHashCode() { } public override bool Equals(object obj) { } public bool Equals(Point3D other) { } public override string ToString() { } } I have tried to break my struct in the way they describe, namely by storing it in a List<Point3D>, as well as changing the value via a method using ref, but I did not encounter they behavior they warn about (maybe a pointer might allow me to break it?). Am I being too cautious in my approach, or should I be okay to use it as is?

    Read the article

  • Culture Sensitive GetHashCode

    - by user114928
    Hi, I'm writing a c# application that will process some text and provide basic query functions. In order to ensure the best possible support for other languages, I am allowing the users of the application to specify the System.Globalization.CultureInfo (via the "en-GB" style code) and also the full range of collation options using the System.Globalization.CompareOptions flags enum. For regular string comparison I'm then using a combination of: a) String.Compare overload that accepts the culture and options b) For some bulk processes I'm caching the byte data (KeyData) from CompareInfo.GetSortKey (overload that accepts the options) and using a byte-by-byte comparison of the KeyData. This seemed fine (although please comment if you think these two methods shouldn't be mixed), but then I had reason to use the HashSet< class which only has an overload for IEqualityComparer<. MS documentation seems to suggest that I should use StringComparer (which implements both IEqualityComparer< and IComparer<), but this only seems to support the "IgnoreCase" option from CompareOptions and not "IgnoreKanaType", "IgnoreSymbols", "IgnoreWidth" etc. I'm assuming that a StringComparer that ignores these other options could produce different hashcodes for two strings that might be considered the same using my other comparison options. I'd therefore get incorrect results from my application. Only thought at the moment is to create my own IEqualityComparer< that generates a hashcode from the SortKey.KeyData and compares eqality be using the String.Compare overload. Any suggestions?

    Read the article

  • Why should the "prime-based" hashcode implmentation be used instead of the "naive" one?

    - by Wilhelm
    I have seen that a prime number implmentation of the GetHashCode function is being recommend, for example here. However using the following code (in VB, sorry), it seems as if that implementation gives the same hash density as a "naive" xor implementation. If the density is the same, I would suppose there is the same probability of cllision in both implementations. Am I missing anything on why is the prime approach preferred? I am supossing that if the hash code is a byte I do not lose generality for the integer case. Sub Main() Dim XorHashes(255) As Integer Dim PrimeHashes(255) As Integer For i = 0 To 255 For j = 0 To 255 For k = 0 To 255 XorHashes(GetXorHash(i, j, k)) += 1 PrimeHashes(GetPrimeHash(i, j, k)) += 1 Next Next Next For i = 0 To 255 Console.WriteLine("{0}: {1}, {2}", i, XorHashes(i), PrimeHashes(i)) Next Console.ReadKey() End Sub Public Function GetXorHash(ByVal valueOne As Integer, ByVal valueTwo As Integer, ByVal valueThree As Integer) As Byte Return CByte((valueOne Xor valueTwo Xor valueThree) Mod 256) End Function Public Function GetPrimeHash(ByVal valueOne As Integer, ByVal valueTwo As Integer, ByVal valueThree As Integer) As Byte Dim TempHash = 17 TempHash = 31 * TempHash + valueOne TempHash = 31 * TempHash + valueTwo TempHash = 31 * TempHash + valueThree Return CByte(TempHash Mod 256) End Function

    Read the article

  • Mocking successive calls of similar type via sequential mocking

    - by mehfuzh
    In this post , i show how you can benefit from  sequential mocking feature[In JustMock] for setting up expectations with successive calls of same type.  To start let’s first consider the following dummy database and entity class. public class Person {     public virtual string Name { get; set; }     public virtual int Age { get; set; } }   public interface IDataBase {     T Get<T>(); } Now, our test goal is to return different entity for successive calls on IDataBase.Get<T>(). By default, the behavior in JustMock is override , which is similar to other popular mocking tools. By override it means that the tool will consider always the latest user setup. Therefore, the first example will return the latest entity every-time and will fail in line #12: Person person1 = new Person { Age = 30, Name = "Kosev" }; Person person2 = new Person { Age = 80, Name = "Mihail" };   var database = Mock.Create<IDataBase>();   Queue<Person> queue = new Queue<Person>();   Mock.Arrange(() => database.Get<Person>()).Returns(() => queue.Dequeue()); Mock.Arrange(() => database.Get<Person>()).Returns(person2);   // this will fail Assert.Equal(person1.GetHashCode(), database.Get<Person>().GetHashCode());   Assert.Equal(person2.GetHashCode(), database.Get<Person>().GetHashCode()); We can solve it the following way using a Queue and that removes the item from bottom on each call: Person person1 = new Person { Age = 30, Name = "Kosev" }; Person person2 = new Person { Age = 80, Name = "Mihail" };   var database = Mock.Create<IDataBase>();   Queue<Person> queue = new Queue<Person>();   queue.Enqueue(person1); queue.Enqueue(person2);   Mock.Arrange(() => database.Get<Person>()).Returns(queue.Dequeue());   Assert.Equal(person1.GetHashCode(), database.Get<Person>().GetHashCode()); Assert.Equal(person2.GetHashCode(), database.Get<Person>().GetHashCode()); This will ensure that right entity is returned but this is not an elegant solution. So, in JustMock we introduced a  new option that lets you set up your expectations sequentially. Like: Person person1 = new Person { Age = 30, Name = "Kosev" }; Person person2 = new Person { Age = 80, Name = "Mihail" };   var database = Mock.Create<IDataBase>();   Mock.Arrange(() => database.Get<Person>()).Returns(person1).InSequence(); Mock.Arrange(() => database.Get<Person>()).Returns(person2).InSequence();   Assert.Equal(person1.GetHashCode(), database.Get<Person>().GetHashCode()); Assert.Equal(person2.GetHashCode(), database.Get<Person>().GetHashCode()); The  “InSequence” modifier will tell the mocking tool to return the expected result as in the order it is specified by user. The solution though pretty simple and but neat(to me) and way too simpler than using a collection to solve this type of cases. Hope that helps P.S. The example shown in my blog is using interface don’t require a profiler  and you can even use a notepad and build it referencing Telerik.JustMock.dll, run it with GUI tools and it will work. But this feature also applies to concrete methods that includes JM profiler and can be implemented for more complex scenarios.

    Read the article

  • Is the .Net HashSet uniqueness calculation completely based on Hash Codes?

    - by RobV
    I was wondering whether the .Net HashSet<T> is based completely on hash codes or whether it uses equality as well? I have a particular class that I may potentially instantiate millions of instances of and there is a reasonable chance that some hash codes will collide at that point. I'm considering using HashSet's to store some instances of this class and am wondering if it's actually worth doing - if the uniqueness of an element is only determined on its hash code then that's of no use to me for real applications MSDN documentation seems to be rather vague on this topic - any enlightenment would be appreciated

    Read the article

1 2 3 4 5 6  | Next Page >