Search Results

Search found 32346 results on 1294 pages for 'method overloading'.

Page 11/1294 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Creating a method that is simultaneously an instance and class method

    - by Mike Axiak
    In Python, I'd like to be able to create a function that behaves both as a class function and an instance method, but with the ability to change behaviors. The use case for this is for a set of serializable objects and types. As an example: >>> class Thing(object): #... >>> Thing.to_json() 'A' >>> Thing().to_json() 'B' I know that given the definition of classmethod() in funcobject.c in the Python source, this looks like it'd be simple with a C module. Is there a way to do this from within python? Thanks!

    Read the article

  • C++, create an instance from a static method

    - by Manux
    Hello, let's say I want my users to use only one class, say SpecialData. Now, this data class would have many methods, and depending on the type of data, the methods do different things, internally, but return externally similar results. Therefore my wanting to have one "public" class and other "private", child classes that would change the behavior of methods, etc... It would be amazingly more simple for some types of data that need to be built to do something like this: SpecialData& sm = SpecialData::new_supermatrix(); and new_supermatrix() would return a SuperMatrix instance, which inherits from most behaviors of SpecialData. my header: static SpecialData& new_supermatrix(); my cpp: SpecialData& SpecialData::new_supermatrix()(){ return SuperMatrix(MATRIX_DEFAULT_MAGNITUDE,1000,1239,FLOAT32,etc...); } The problem is, I get this error, which is probably logical due to the circumstances: invalid initialization of non-const reference of type ‘SpecialData&’ from a temporary of type ‘SpecialData’ So, any ideas?

    Read the article

  • PHP OOP: method?

    - by Isis
    Hello <?php class Templater { static $params = array(); public static function assign($name, $value) { self::$params[] = array($name => $value); } public static function draw() { self::$params; } } $test = Templater::assign('key', 'value'); $test = Templater::draw(); print_r($test); How to alter this script so I could use this:? $test = Templater::assign('key', 'value')->assign('key2', 'value2')-draw(); print_r($test);

    Read the article

  • Method to register method to be called when event is raised

    - by zaidwaqi
    I have a Panel which contains 20 PictureBox controls. If a user clicks on any of the controls, I want a method within the Panel to be called. How do I do this? public class MyPanel : Panel { public MyPanel() { for(int i = 0; i < 20; i++) { Controls.Add(new PictureBox()); } } // DOESN'T WORK. // function to register functions to be called if the pictureboxes are clicked. public void RegisterFunction( <function pointer> func ) { foreach ( Control c in Controls ) { c.Click += new EventHandler( func ); } } } How do I implement RegisterFunction()? Also, if there are cool C# features that can make the code more elegant, please share.

    Read the article

  • Oracle Unified Method (OUM) Release 5.6

    - by user714714
    ORACLE® UNIFIED METHOD RELEASE 5.6 Oracle’s Full Lifecycle Methodfor Deploying Oracle-Based Business Solutions About | Release | Access | Previous Announcements About Oracle is evolving the Oracle® Unified Method (OUM) to achieve the vision of supporting the entire Enterprise IT Lifecycle, including support for the successful implementation of every Oracle product. OUM replaces Legacy Methods, such as AIM Advantage, AIM for Business Flows, EMM Advantage, PeopleSoft's Compass, and Siebel's Results Roadmap. OUM provides an implementation approach that is rapid, broadly adaptive, and business-focused. OUM includes a comprehensive project and program management framework and materials to support Oracle's growing focus on enterprise-level IT strategy, architecture, and governance. Release OUM release 5.6 provides support for Application Implementation, Cloud Application Implementation, and Software Upgrade projects as well as the complete range of technology projects including Business Intelligence (BI) and Enterprise Performance Management (EPM), Enterprise Security, WebCenter, Service-Oriented Architecture (SOA), Application Integration Architecture (AIA), Business Process Management (BPM), Enterprise Integration, and Custom Software. Detailed techniques and tool guidance are provided, including a supplemental guide related to Oracle Tutor and UPK. This release features: Business Process Management (BPM) Project Engineering Supplemental Guide Cloud Roadmap View and Supplemental Guide Enterprise Security View and Supplemental Guide Service-Oriented Architecture (SOA) Governance Implementation Supplemental Guide "Tailoring OUM for Your Project" White Paper OUM Microsoft Project Workplan Template and User's Guide Mappings: OUM to J.D. Edwards OneMethodology, OUM Roles to Task Techniques: Determining Number of Iterations, Managing an OUM Project using Scrum Templates: Scrum Workplan (WM.010), Siebel CRM Enhanced / Updated: Manage Focus Area reorganized by Activities for all Views Oracle Architecture Development Process (OADP) View updated for OADP v3.0 Oracle Support Services Supplemental Guide expanded to include guidance related to IT Change Management Oracle User Productivity Kit Professional (UPK Pro) and Tutor Supplemental Guide expanded guidance for UPK Pro Service-Oriented Architecture (SOA) Application Integration Architecture (AIA) Supplemental Guide updated for SOA Tactical Project Delivery View Service-Oriented Architecture (SOA) Tactical Project Delivery View expanded to include additional tasks Siebel CRM Supplemental Guide expanded task guidance and added select Siebel-specific OUM templates WebCenter View and Supplemental Guide updated for WebCenter Portal and Content Management For a comprehensive list of features and enhancements, refer to the "What's New" page of the Method Pack. Upcoming releases will provide expanded support for Oracle's Enterprise Application suites including product-suite specific materials and guidance for tailoring OUM to support various engagement types. Access Oracle Customers Oracle customers may obtain copies of the method for their internal use – including guidelines, templates, and tailored work breakdown structure – by contracting with Oracle for a consulting engagement of two weeks or longer and meeting some additional minimum criteria. Customers, who have a signed consulting contract with Oracle and meet the engagement qualification criteria, are permitted to download the current release of OUM for their perpetual use. They may also obtain subsequent releases published during a renewable, three-year access period. Training courses are also available to these customers. Contact your local Oracle Sales Representative about enrolling in the OUM Customer Program. Oracle PartnerNetwork (OPN) Diamond, Platinum, and Gold Partners OPN Diamond, Platinum, and Gold Partners are able to access the OUM method pack, training courses, and collateral from the OPN Portal at no additional cost: Go to the OPN Portal at partner.oracle.com. Select the "Partners (Login Required)" tab. Login. Select the "Engage with Oracle" tab. From the Engage with Oracle page, locate the "Applications" heading. From the Applications heading, locate and select the "Oracle Unified Method" link. From the Oracle Unified Method Knowledge Zone, select the "Implement" tab. From the Implement tab, select the "Tools and Resources" link. Locate and select the "Oracle Unified Method (OUM)" link. Previous Announcements Oracle Unified Method (OUM) Release 5.6 Oracle Unified Method (OUM) Release 5.5 Oracle Unified Method (OUM) Release 5.4 Oracle EMM Advantage Retired Retirement of Oracle EMM Advantage Planned for December 01, 2011

    Read the article

  • Method binding to base method in external library can't handle new virtual methods "between"

    - by Berg
    Lets say I have a library, version 1.0.0, with the following contents: public class Class1 { public virtual void Test() { Console.WriteLine( "Library:Class1 - Test" ); Console.WriteLine( "" ); } } public class Class2 : Class1 { } and I reference this library in a console application with the following contents: class Program { static void Main( string[] args ) { var c3 = new Class3(); c3.Test(); Console.ReadKey(); } } public class Class3 : ClassLibrary1.Class2 { public override void Test() { Console.WriteLine("Console:Class3 - Test"); base.Test(); } } Running the program will output the following: Console:Class3 - Test Library:Class1 - Test If I build a new version of the library, version 2.0.0, looking like this: public class Class1 { public virtual void Test() { Console.WriteLine( "Library:Class1 - Test V2" ); Console.WriteLine( "" ); } } public class Class2 : Class1 { public override void Test() { Console.WriteLine("Library:Class2 - Test V2"); base.Test(); } } and copy this version to the bin folder containing my console program and run it, the results are: Console:Class3 - Test Library:Class1 - Test V2 I.e, the Class2.Test method is never executed, the base.Test call in Class3.Test seems to be bound to Class1.Test since Class2.Test didn't exist when the console program was compiled. This was very surprising to me and could be a big problem in situations where you deploy new versions of a library without recompiling applications. Does anyone else have experience with this? Are there any good solutions? This makes it tempting to add empty overrides that just calls base in case I need to add some code at that level in the future...

    Read the article

  • calling asp.net mvc action method using jquery post method expires the session

    - by nccsbim071
    hi, i have a website where i provicde a link. On clicking the link a controller action method is called to generate a zip file after creation of zip file is done, i show the link to download the zip file by replacing the link to create a zip with the link to download the zip. the problem is that after zip file creation is over and link is shown, when user clicks on the link to download the zip file, they are sent to login. After providing correct credentials in the login page they are prompted to download the zip file. they sould not be sent to the login page. In the action to generate zip file i haven't abondoned the session or haven't not done anything that abondons the session. the user should not be sen't to login page after successful creation of zip file user should be able to download the file without login. i search internet on this problem, but i did not find any solution. In one of the blog written by hanselman i found this statement that creates the problem with the session: Is some other thing like an Ajax call or IE's Content Advisor simultaneously hitting the default page or login page and causing a race condition that calls Session.Abandon? (It's happened before!) so i thought there might be some problem with ajax call that causes the session to expire, but i don't know what is happening? any help please thanks

    Read the article

  • TPL - Using static method vs struct method

    - by Sunit
    I have about 1500 files on a share for which I need to collect FileVersionInfo string. So I created a Static method in my Gateway like this: private static string GetVersionInfo(string filepath) { FileVersionInfo verInfo = FileVersionInfo.GetVersionInfo(filepath); return string.Format("{0}.{1}.{2}.{3}", verInfo.ProductMajorPart, verInfo.ProductMinorPart, verInfo.ProductBuildPart, verInfo.ProductPrivatePart).Trim(); } And then used FileAndVersion struct in a PLINQ call with DegreeOfParallelism as this is I/O related resultList = dllFilesRows.AsParallel().WithDegreeOfParallelism(20) .Select(r => { var symbolPath = r.Filename; return new FilenameAndVersion{Filename=symbolPath, Version=GetVersionInfo(symbolPath)}; }) .ToArray(); Later I modified the Struct, FileAndVersion as: private struct FilenameAndVersion { private string _version, _filename; public string Version { get { return _version; } } public string Filename { get { return _filename; } } public void SetVersion() { FileVersionInfo verInfo = FileVersionInfo.GetVersionInfo(this.Filename); this._version = string.Format("{0}.{1}.{2}.{3}", verInfo.ProductMajorPart, verInfo.ProductMinorPart, verInfo.ProductBuildPart, verInfo.ProductPrivatePart).Trim(); } public FilenameAndVersion(string filename, string version) { this._filename = filename; this._version = string.Empty; SetVersion(); } } And used it: resultList = dllFilesRows.AsParallel().WithDegreeOfParallelism(20) .Select(r => { var symbolPath = r.Filename; return new FilenameAndVersion(symbolPath, String.Empty); }) .ToArray(); The question is, is this going to help me in anyway and is a good pattern to use ? Sunit

    Read the article

  • How can I Setup overloaded method invocations in Moq?

    - by arootbeer
    I'm trying to mock a mapping interface IMapper: public interface IMapper<TFoo, TBar> { TBar Map(TFoo foo); TFoo Map(TBar bar); } In my test, I'm setting the mock mapper up to expect an invocation of each (around an NHibernate update operation): //... _mapperMock.Setup(m => m.Map(fooMock.Object)).Returns(barMock.Object); _mapperMock.Setup(m => m.Map(barMock.Object)).Returns(fooMock.Object); //... However, when the second Map invocation is made, the mapper mock throws because it is only expecting a single invocation. Watching the mapper mock during setup at runtime, I can look see the Map(TFoo foo) overload get registered, and then see it get replaced when the Map(TBar bar) overload is set up. Is this a problem with the way Moq handles setup, or is there a different syntax I need to use in this case?

    Read the article

  • Multiple asynchronous method calls to method while in a loop

    - by ranabra
    I have spent a whole day trying various ways using 'AddOnPreRenderCompleteAsync' and 'RegisterAsyncTask' but no success so far. I succeeded making the call to the DB asynchronous using 'BeginExecuteReader' and 'EndExecuteReader' but that is missing the point. The asynch handling should not be the call to the DB which in my case is fast, it should be afterwards, during the 'while' loop, while calling an external web-service. I think the simplified pseudo code will explain best: (Note: the connection string is using 'MultipleActiveResultSets') "Select ID, UserName from MyTable" 'Open connection to DB ExecuteReader(); if (DR.HasRows) {     while (DR.Read())     {         'Call external web-service         'and get current Temperature of each UserName - DR["UserName"].ToString()         'Update my local DB         Update MyTable set Temperature = ValueFromWebService where UserName =                                       DR["UserName"]         CmdUpdate.ExecuteNonQuery();     }     'Close connection etc } Accessing the DB is fast. Getting the returned result from the external web-service is slow and that at least should be handled Asynchnously. If each call to the web service takes just 1 second, assuming I have only 100 users it will take minimum 100 seconds for the DB update to complete, which obviously is not an option. There eventually should be thousands of users (currently only 2). Currently everything works, just very synchnously :) Thoughts to myself: Maybe my way of approaching this is wrong? Maybe the entire process should be called Asynchnously Many thanx

    Read the article

  • Example: Objective C method alongside a php method

    - by Nic Hubbard
    I am very used to javascript and php programing, and I just jumped into programing Objective C. After working with it for a few weeks, the methods still confused me, as to how it is passing params, and how the methods are named. Since I am used to php, I am used to seeing: function myFunc($param1, $param2, $param3, $param4) { return FALSE; } Could someone show me how this would be written in Objective C, so that I can get used to writing methods that have parameters?

    Read the article

  • how to change UIKit UIImage:drawInRect method to AppKIt NSImage:drawInRect Method

    - by user322111
    Hi, i'm porting an iphone app to Mac app,there i have to change all the UIKit related class to AppKit. if you can help me on this really appreciate. is this the best way to do below part.. Iphone App--using UIKit UIGraphicsPushContext(ctx); [image drawInRect:rect]; UIGraphicsPopContext(); Mac Os--Using AppKit [NSGraphicsContext saveGraphicsState]; NSGraphicsContext * nscg = [NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:YES]; [NSGraphicsContext setCurrentContext:nscg]; NSRect rect = NSMakeRect(offset.x * scale, offset.y * scale, scale * size.width, scale * size.height); [NSGraphicsContext restoreGraphicsState]; [image drawInRect:rect fromRect:NSMakeRect( 0, 0, [image size].width, [image size].height ) operation:NSCompositeClear fraction:1.0];

    Read the article

  • += new EventHandler(Method) vs += Method

    - by mafutrct
    There are two basic ways to subscribe to an event: SomeEvent += new EventHandler<ArgType> (MyHandlerMethod); SomeEvent += MyHandlerMethod; What is the difference, and when should I chose one over the other? Edit: If it is the same, then why does VS default to the long version, cluttering the code? That makes no sense at all to me.

    Read the article

  • Problem calling method inside same method in php?

    - by Fero
    Hi all, Will any one please tell me how to run this class. I am getting the FATAL ERROR: Fatal error: Call to undefined function readnumber() in E:\Program Files\xampp\htdocs\numberToWords\numberToWords.php on line 20 while giving input as 120 <?php class Test { function readnumber($num, $depth) { $num = (int)$num; $retval =""; if ($num < 0) // if it's any other negative, just flip it and call again return "negative " + readnumber(-$num, 0); if ($num > 99) // 100 and above { if ($num > 999) // 1000 and higher $retval .= readnumber($num/1000, $depth+3); $num %= 1000; // now we just need the last three digits if ($num > 99) // as long as the first digit is not zero $retval .= readnumber($num/100, 2)." hundred\n"; $retval .=readnumber($num%100, 1); // our last two digits } else // from 0 to 99 { $mod = floor($num / 10); if ($mod == 0) // ones place { if ($num == 1) $retval.="one"; else if ($num == 2) $retval.="two"; else if ($num == 3) $retval.="three"; else if ($num == 4) $retval.="four"; else if ($num == 5) $retval.="five"; else if ($num == 6) $retval.="six"; else if ($num == 7) $retval.="seven"; else if ($num == 8) $retval.="eight"; else if ($num == 9) $retval.="nine"; } else if ($mod == 1) // if there's a one in the ten's place { if ($num == 10) $retval.="ten"; else if ($num == 11) $retval.="eleven"; else if ($num == 12) $retval.="twelve"; else if ($num == 13) $retval.="thirteen"; else if ($num == 14) $retval.="fourteen"; else if ($num == 15) $retval.="fifteen"; else if ($num == 16) $retval.="sixteen"; else if ($num == 17) $retval.="seventeen"; else if ($num == 18) $retval.="eighteen"; else if ($num == 19) $retval.="nineteen"; } else // if there's a different number in the ten's place { if ($mod == 2) $retval.="twenty "; else if ($mod == 3) $retval.="thirty "; else if ($mod == 4) $retval.="forty "; else if ($mod == 5) $retval.="fifty "; else if ($mod == 6) $retval.="sixty "; else if ($mod == 7) $retval.="seventy "; else if ($mod == 8) $retval.="eighty "; else if ($mod == 9) $retval.="ninety "; if (($num % 10) != 0) { $retval = rtrim($retval); //get rid of space at end $retval .= "-"; } $retval.=readnumber($num % 10, 0); } } if ($num != 0) { if ($depth == 3) $retval.=" thousand\n"; else if ($depth == 6) $retval.=" million\n"; if ($depth == 9) $retval.=" billion\n"; } return $retval; } } $objTest = new Test(); $objTest->readnumber(120,0); ?>

    Read the article

  • Calling overridden method from within overriding method in OO PHP

    - by paddymcc
    Working in a symfony model, I want to override a function and call the overridden function from within the overriding one, along the lines of class MyClass extends BaseMyClass { function setMyProperty($p) { parent::setMyProperty($p); //do some other stuff } } This is resulting in a segmentation fault. I don't want to alter the parent class - it's been generated by symfony, and may feasibly be overwritten in the future if the model is rebuilt. This seems like something that should be straightforward, but I'm struggling to find the solution. Thanks for any advice

    Read the article

  • C++: Create abstract class with abstract method and override the method in a subclass

    - by Martijn Courteaux
    Hi, How to create in C++ an abstract class with some abstract methods that I want to override in a subclass? How should the .h file look? Is there a .cpp, if so how should it look? In Java it would look like this: abstract class GameObject { public abstract void update(); public abstract void paint(Graphics g); } class Player extends GameObject { @Override public void update() { // ... } @Override public void paint(Graphics g) { // ... } } // In my game loop: for (int i = 0; i < objects.size(); i++) { objects.get(i).update(); } for (int i = 0; i < objects.size(); i++) { objects.get(i).paint(g); } Translating this code to C++ is enough for me.

    Read the article

  • Using [self method] or @selector(method)?

    - by fuzzygoat
    Can anyone enlighten me as to the differences between the two statements below. [self playButtonSound]; AND: [self performSelector:@selector(playButtonSound)]; I am just asking as I had some old code that used @selector, now with a little more knowledge I can't think why I did not use [self playButtonSound] instead, they both seem to do the same as written here. gary

    Read the article

  • How to call a method in init method ?

    - by srikanth rongali
    My program looks like this: -(id)init { if ( (self = [super init]) ) { //TargetWithActions *targetActions= [[TargetWithActions alloc] init]; [self countDownSpeed123]; } return self; } -(void)countDownSpeed123 { countDownSpeed = 5.0f; } @end warning: 'TargetWithActions' may not respond to '-countDownSpeed123' I am getting the warning in this way. Where I am wrong in my program. Please explain ? Thank You.

    Read the article

  • Overriding or overloading?

    - by atch
    Guys I know this question is silly but just to make sure: Having in my class method: boolean equal(Document d) { //do something } I'm overloading this method nor overriding right? I know that this or similiar question will be on upcoming egzam and would be stupid to not get points for such a simple mistake;

    Read the article

  • Function overloading

    - by makcoozi
    I found this code , and i m not sure that whether overloading should happen or not. void print( int (*arr)[6], int size ); void print( int (*arr)[5], int size ); what happens if I pass pointer to an array of 4 elements , to it should come... any thread will be helpful.

    Read the article

  • LINQ – SequenceEqual() method

    - by nmarun
    I have been looking at LINQ extension methods and have blogged about what I learned from them in my blog space. Next in line is the SequenceEqual() method. Here’s the description about this method: “Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.” Let’s play with some code: 1: int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 2: // int[] numbersCopy = numbers; 3: int[] numbersCopy = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 4:  5: Console.WriteLine(numbers.SequenceEqual(numbersCopy)); This gives an output of ‘True’ – basically compares each of the elements in the two arrays and returns true in this case. The result is same even if you uncomment line 2 and comment line 3 (I didn’t need to say that now did I?). So then what happens for custom types? For this, I created a Product class with the following definition: 1: class Product 2: { 3: public int ProductId { get; set; } 4: public string Name { get; set; } 5: public string Category { get; set; } 6: public DateTime MfgDate { get; set; } 7: public Status Status { get; set; } 8: } 9:  10: public enum Status 11: { 12: Active = 1, 13: InActive = 2, 14: OffShelf = 3, 15: } In my calling code, I’m just adding a few product items: 1: private static List<Product> GetProducts() 2: { 3: return new List<Product> 4: { 5: new Product 6: { 7: ProductId = 1, 8: Name = "Laptop", 9: Category = "Computer", 10: MfgDate = new DateTime(2003, 4, 3), 11: Status = Status.Active, 12: }, 13: new Product 14: { 15: ProductId = 2, 16: Name = "Compact Disc", 17: Category = "Water Sport", 18: MfgDate = new DateTime(2009, 12, 3), 19: Status = Status.InActive, 20: }, 21: new Product 22: { 23: ProductId = 3, 24: Name = "Floppy", 25: Category = "Computer", 26: MfgDate = new DateTime(1993, 3, 7), 27: Status = Status.OffShelf, 28: }, 29: }; 30: } Now for the actual check: 1: List<Product> products1 = GetProducts(); 2: List<Product> products2 = GetProducts(); 3:  4: Console.WriteLine(products1.SequenceEqual(products2)); This one returns ‘False’ and the reason is simple – this one checks for reference equality and the products in the both the lists get different ‘memory addresses’ (sounds like I’m talking in ‘C’). In order to modify this behavior and return a ‘True’ result, we need to modify the Product class as follows: 1: class Product : IEquatable<Product> 2: { 3: public int ProductId { get; set; } 4: public string Name { get; set; } 5: public string Category { get; set; } 6: public DateTime MfgDate { get; set; } 7: public Status Status { get; set; } 8:  9: public override bool Equals(object obj) 10: { 11: return Equals(obj as Product); 12: } 13:  14: public bool Equals(Product other) 15: { 16: //Check whether the compared object is null. 17: if (ReferenceEquals(other, null)) return false; 18:  19: //Check whether the compared object references the same data. 20: if (ReferenceEquals(this, other)) return true; 21:  22: //Check whether the products' properties are equal. 23: return ProductId.Equals(other.ProductId) 24: && Name.Equals(other.Name) 25: && Category.Equals(other.Category) 26: && MfgDate.Equals(other.MfgDate) 27: && Status.Equals(other.Status); 28: } 29:  30: // If Equals() returns true for a pair of objects 31: // then GetHashCode() must return the same value for these objects. 32: // read why in the following articles: 33: // http://geekswithblogs.net/akraus1/archive/2010/02/28/138234.aspx 34: // http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overriden-in-c 35: public override int GetHashCode() 36: { 37: //Get hash code for the ProductId field. 38: int hashProductId = ProductId.GetHashCode(); 39:  40: //Get hash code for the Name field if it is not null. 41: int hashName = Name == null ? 0 : Name.GetHashCode(); 42:  43: //Get hash code for the ProductId field. 44: int hashCategory = Category.GetHashCode(); 45:  46: //Get hash code for the ProductId field. 47: int hashMfgDate = MfgDate.GetHashCode(); 48:  49: //Get hash code for the ProductId field. 50: int hashStatus = Status.GetHashCode(); 51: //Calculate the hash code for the product. 52: return hashProductId ^ hashName ^ hashCategory & hashMfgDate & hashStatus; 53: } 54:  55: public static bool operator ==(Product a, Product b) 56: { 57: // Enable a == b for null references to return the right value 58: if (ReferenceEquals(a, b)) 59: { 60: return true; 61: } 62: // If one is null and the other not. Remember a==null will lead to Stackoverflow! 63: if (ReferenceEquals(a, null)) 64: { 65: return false; 66: } 67: return a.Equals((object)b); 68: } 69:  70: public static bool operator !=(Product a, Product b) 71: { 72: return !(a == b); 73: } 74: } Now THAT kinda looks overwhelming. But lets take one simple step at a time. Ok first thing you’ve noticed is that the class implements IEquatable<Product> interface – the key step towards achieving our goal. This interface provides us with an ‘Equals’ method to perform the test for equality with another Product object, in this case. This method is called in the following situations: when you do a ProductInstance.Equals(AnotherProductInstance) and when you perform actions like Contains<T>, IndexOf() or Remove() on your collection Coming to the Equals method defined line 14 onwards. The two ‘if’ blocks check for null and referential equality using the ReferenceEquals() method defined in the Object class. Line 23 is where I’m doing the actual check on the properties of the Product instances. This is what returns the ‘True’ for us when we run the application. I have also overridden the Object.Equals() method which calls the Equals() method of the interface. One thing to remember is that anytime you override the Equals() method, its’ a good practice to override the GetHashCode() method and overload the ‘==’ and the ‘!=’ operators. For detailed information on this, please read this and this. Since we’ve overloaded the operators as well, we get ‘True’ when we do actions like: 1: Console.WriteLine(products1.Contains(products2[0])); 2: Console.WriteLine(products1[0] == products2[0]); This completes the full circle on the SequenceEqual() method. See the code used in the article here.

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >