Search Results

Search found 31989 results on 1280 pages for 'method'.

Page 7/1280 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • 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

  • 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

  • Customizable Method Bodies in NetBeans IDE 7.3

    - by Geertjan
    In NetBeans IDE 7.3, bodies of newly created methods can now be customized in Tools/Templates/Java/Code Snippets, see below: The content of the first of the two above, "Generated Method Body", is like this: <#-- A built-in Freemarker template (see http://freemarker.sourceforge.net) used for filling the body of methods generated by the IDE. When editing the template, the following predefined variables, that will be then expanded into the corresponding values, could be used together with Java expressions and comments: ${method_return_type}       a return type of a created method ${default_return_value}     a value returned by the method by default ${method_name}              name of the created method ${class_name}               qualified name of the enclosing class ${simple_class_name}        simple name of the enclosing class --> throw new java.lang.UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. The second one, "Overriden Methody Body", is as follows: <#-- A built-in Freemarker template (see http://freemarker.sourceforge.net) used for filling the body of overridden methods generated by the IDE. When editing the template, the following predefined variables, that will be then expanded into the corresponding values, could be used together with Java expressions and comments: ${super_method_call}        a super method call ${method_return_type}       a return type of a created method ${default_return_value}     a value returned by the method by default ${method_name}              name of the created method ${class_name}               qualified name of the enclosing class ${simple_class_name}        simple name of the enclosing class --> <#if method_return_type?? && method_return_type != "void"> return ${super_method_call}; //To change body of generated methods, choose Tools | Templates. <#else> ${super_method_call}; //To change body of generated methods, choose Tools | Templates. </#if>

    Read the article

  • Parallelism in .NET – Part 8, PLINQ’s ForAll Method

    - by Reed
    Parallel LINQ extends LINQ to Objects, and is typically very similar.  However, as I previously discussed, there are some differences.  Although the standard way to handle simple Data Parellelism is via Parallel.ForEach, it’s possible to do the same thing via PLINQ. PLINQ adds a new method unavailable in standard LINQ which provides new functionality… LINQ is designed to provide a much simpler way of handling querying, including filtering, ordering, grouping, and many other benefits.  Reading the description in LINQ to Objects on MSDN, it becomes clear that the thinking behind LINQ deals with retrieval of data.  LINQ works by adding a functional programming style on top of .NET, allowing us to express filters in terms of predicate functions, for example. PLINQ is, generally, very similar.  Typically, when using PLINQ, we write declarative statements to filter a dataset or perform an aggregation.  However, PLINQ adds one new method, which provides a very different purpose: ForAll. The ForAll method is defined on ParallelEnumerable, and will work upon any ParallelQuery<T>.  Unlike the sequence operators in LINQ and PLINQ, ForAll is intended to cause side effects.  It does not filter a collection, but rather invokes an action on each element of the collection. At first glance, this seems like a bad idea.  For example, Eric Lippert clearly explained two philosophical objections to providing an IEnumerable<T>.ForEach extension method, one of which still applies when parallelized.  The sole purpose of this method is to cause side effects, and as such, I agree that the ForAll method “violates the functional programming principles that all the other sequence operators are based upon”, in exactly the same manner an IEnumerable<T>.ForEach extension method would violate these principles.  Eric Lippert’s second reason for disliking a ForEach extension method does not necessarily apply to ForAll – replacing ForAll with a call to Parallel.ForEach has the same closure semantics, so there is no loss there. Although ForAll may have philosophical issues, there is a pragmatic reason to include this method.  Without ForAll, we would take a fairly serious performance hit in many situations.  Often, we need to perform some filtering or grouping, then perform an action using the results of our filter.  Using a standard foreach statement to perform our action would avoid this philosophical issue: // Filter our collection var filteredItems = collection.AsParallel().Where( i => i.SomePredicate() ); // Now perform an action foreach (var item in filteredItems) { // These will now run serially item.DoSomething(); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } This would cause a loss in performance, since we lose any parallelism in place, and cause all of our actions to be run serially. We could easily use a Parallel.ForEach instead, which adds parallelism to the actions: // Filter our collection var filteredItems = collection.AsParallel().Where( i => i.SomePredicate() ); // Now perform an action once the filter completes Parallel.ForEach(filteredItems, item => { // These will now run in parallel item.DoSomething(); }); This is a noticeable improvement, since both our filtering and our actions run parallelized.  However, there is still a large bottleneck in place here.  The problem lies with my comment “perform an action once the filter completes”.  Here, we’re parallelizing the filter, then collecting all of the results, blocking until the filter completes.  Once the filtering of every element is completed, we then repartition the results of the filter, reschedule into multiple threads, and perform the action on each element.  By moving this into two separate statements, we potentially double our parallelization overhead, since we’re forcing the work to be partitioned and scheduled twice as many times. This is where the pragmatism comes into play.  By violating our functional principles, we gain the ability to avoid the overhead and cost of rescheduling the work: // Perform an action on the results of our filter collection .AsParallel() .Where( i => i.SomePredicate() ) .ForAll( i => i.DoSomething() ); The ability to avoid the scheduling overhead is a compelling reason to use ForAll.  This really goes back to one of the key points I discussed in data parallelism: Partition your problem in a way to place the most work possible into each task.  Here, this means leaving the statement attached to the expression, even though it causes side effects and is not standard usage for LINQ. This leads to my one guideline for using ForAll: The ForAll extension method should only be used to process the results of a parallel query, as returned by a PLINQ expression. Any other usage scenario should use Parallel.ForEach, instead.

    Read the article

  • One method with many behaviours or many methods

    - by Krowar
    This question is quite general and not related to a specific language, but more to coding best practices. Recently, I've been developing a feature for my app that is requested in many cases with slightly different behaviours. This function send emails , but to different receivers, or with different texts according to the parameters. The method signature is something like public static sendMail (t_message message = null , t_user receiver = null , stream attachedPiece = null) And then there are many condition inside the method, like if(attachedPiece != null) { } I've made the choice to do it this way (with a single method) because it prevents me to rewrite the (nearly) same method 10 times, but I'm not sure that it's a good practice. What should I have done? Write 10 sendMail method with different parameters? Are there obvious pros and cons for these different ways of programming? Thanks a lot.

    Read the article

  • templated method on T inside a templated class on TT : Is that possible/correct.

    - by paercebal
    I have a class MyClass which is templated on typename T. But inside, I want a method which is templated on another type TT (which is unrelated to T). After reading/tinkering, I found the following notation: template <typename T> class MyClass { public : template<typename TT> void MyMethod(const TT & param) ; } ; For stylistic reasons (I like to have my templated class declaration in one header file, and the method definitions in another header file), I won't define the method inside the class declaration. So, I have to write it as: template <typename T> // this is the type of the class template <typename TT> // this is the type of the method void MyClass<T>::MyMethod(const TT & param) { // etc. } I knew I had to "declare" the typenames used in the method, but didn't know how exactly, and found through trials and errors. The code above compiles on Visual C++ 2008, but: Is this the correct way to have a method templated on TT inside a class templated on T? As a bonus: Are there hidden problems/surprises/constraints behind this kind of code? (I guess the specializations can be quite amusing to write)

    Read the article

  • Is it possible to implement X-HTTP-Method-Override in ASP.NET MVC?

    - by Greg Beech
    I'm implementing a prototype of a RESTful API using ASP.NET MVC and apart from the odd bug here and there I've achieve all the requirements I set out at the start, apart from callers being able to use the X-HTTP-Method-Override custom header to override the HTTP method. What I'd like is that the following request... GET /someresource/123 HTTP/1.1 X-HTTP-Method-Override: DELETE ...would be dispatched to my controller method that implements the DELETE functionality rather than the GET functionality for that action (assuming that there are multiple methods implementing the action, and that they are marked with different [AcceptVerbs] attributes). So, given the following two methods, I would like the above request to be dispatched to the second one: [ActionName("someresource")] [AcceptVerbs(HttpVerbs.Get)] public ActionResult GetSomeResource(int id) { /* ... */ } [ActionName("someresource")] [AcceptVerbs(HttpVerbs.Delete)] public ActionResult DeleteSomeResource(int id) { /* ... */ } Does anybody know if this is possible? And how much work would it be to do so...?

    Read the article

  • Where To Call Custom Method? viewDidLoad, viewWillLoad...

    - by Chris
    I am loading some info from a server. I have created a separate method to do this. I am then calling [self myCustomMethod] to run the method. No matter where I call [self myCustomMethod] (initWithNibName, viewDidLoad, viewWillLoad, viewWillAppear, viewDidAppear), the custom method is getting called twice - what's the deal?

    Read the article

  • Javascript static method intheritance

    - by Matteo Pagliazzi
    I want to create a javascript class/object that allow me to have various method: Model class Model.all() » static method Model.find() » static method Model delete() » instance method Model save() » instance method Model.create() » static that returns a new Model instance For static method I can define them using: Model.staticMethod(){ method } while for instance method is better to use: function Model(){ this.instanceMethod = function(){} } and then create a new instance or using prototype? var m = function Model(){ } m.prototype.method() = function(){ } Now let's say that I want to create a new class based on Model, how to inherit not only its prototypes but also its static methods?

    Read the article

  • Is any simple way to create method and set its body dynamically in C#?

    - by greatromul
    I hold body of method in string. I want to create method dynamically. But I don't know, how to set its body. I saw very tedious way using CodeDom. And I saw using Emit with OpCodes. Is any way to use ready code from string variable? string method_body = "return \"Hello, world!\";"; //there is method body DynamicMethod dm = new System.Reflection.Emit.DynamicMethod("My_method", typeof(string), new Type[] { }); //any way to create method dynamically //any way to set body string result = (string)dm.Invoke(...); //I need write result in variable

    Read the article

  • In Ruby, why is a method invocation not able to be treated as a unit when "do" and "end" is used?

    - by Jian Lin
    The following question is related to the question "Ruby Print Inject Do Syntax". My question is, can we insist on using do and end and make it work with puts or p? This works: a = [1,2,3,4] b = a.inject do |sum, x| sum + x end puts b # prints out 10 so, is it correct to say, inject is an instance method of the Array object, and this instance method takes a block of code, and then returns a number. If so, then it should be no different from calling a function or method and getting back a return value: b = foo(3) puts b or b = circle.getRadius() puts b In the above two cases, we can directly say puts foo(3) puts circle.getRadius() so, there is no way to make it work directly by using the following 2 ways: a = [1,2,3,4] puts a.inject do |sum, x| sum + x end but it gives ch01q2.rb:7:in `inject': no block given (LocalJumpError) from ch01q2.rb:4:in `each' from ch01q2.rb:4:in `inject' from ch01q2.rb:4 grouping the method call using ( ) doesn't work either: a = [1,2,3,4] puts (a.inject do |sum, x| sum + x end) and this gives: ch01q3.rb:4: syntax error, unexpected kDO_BLOCK, expecting ')' puts (a.inject do |sum, x| ^ ch01q3.rb:4: syntax error, unexpected '|', expecting '=' puts (a.inject do |sum, x| ^ ch01q3.rb:6: syntax error, unexpected kEND, expecting $end end) ^ finally, the following version works: a = [1,2,3,4] puts a.inject { |sum, x| sum + x } but why doesn't the grouping of the method invocation using ( ) work in the earlier example? What if a programmer insist that he uses do and end, can it be made to work?

    Read the article

  • Call instance method with objc_msgSend

    - by user772349
    I'm trying to use the objc_msgSend method to call some method dynamically. Say I want call some method in Class B from Class A and there are two methods in class B like: - (void) instanceTestWithStr1:(NSString *)str1 str2:(NSString *)str1; + (void) methodTestWithStr1:(NSString *)str1 str2:(NSString *)str1; And I can call the class method like this in Class A successfully: objc_msgSend(objc_getClass("ClassB"), sel_registerName("methodTestWithStr1:str2:"), @"111", @"222"); And I can call the instance method like this in Class A successfully as well: objc_msgSend([[objc_getClass("ClassB") alloc] init], sel_registerName("instanceTestWithStr1:str2:"), @"111", @"222"); But the thing is to get a instance of Class B I have to call "initWithXXXXX:XXXXXX:XXXXXX" instead of "init" so that to pass some necessary parameters to class B to do the init stuff. So I stored a instance of ClassB in class A as variable: self.classBInstance = [[ClassB alloc] initWithXXXXX:XXXXXX:XXXXXX]; And then I call the method like this (successfully): The problem is, I want to call a method by simply applying the classname and the method sel like "ClassName" and "SEL" and then call it dynamically: If it's a class method. then call it like: objc_msgSend(objc_getClass("ClassName"), sel_registerName("SEL")); If it's a instance method, find the existing class instance variable in the calling class then: objc_msgSend([self.classInstance, sel_registerName("SEL")); So I want to know if there is any way to: Check if a class has a given method (I found "responseToSelector" will be the one) Check if a given method in class method or instance method (maybe can use responseToSelector as well) Check if a class has a instance variable of a given class So I can call a instance method like: objc_msgSend(objc_getClassInstance(self, "ClassB"), sel_registerName("SEL"));

    Read the article

  • UPK and the Oracle Unified Method can be used to deploy Oracle-Based Business Solutions

    - by Emily Chorba
    Originally developed to support Oracle's acquisition strategy, the Oracle Unified Method (OUM) defines a common implementation language across all of Oracle's products and technologies. OUM is a flexible, scalable, and evolving body of knowledge that combines existing best practices and field experience with an industry standard framework that includes the latest thinking around agile implementation and cloud computing.    Strong, proven methods are essential to ensuring successful enterprise IT projects both within Oracle and for our customers and partners. OUM provides a collection of repeatable processes that are the basis for agile implementations of Oracle enterprise business solutions. OUM also provides a structure for tracking progress and managing cost and risks. OUM is applicable to any size or type of IT project. While OUM is a plan-based method—including overview material, task and artifact descriptions, and templates—the method is intended to be tailored to support the appropriate level of ceremony (or agility) required for each project. Guidance is provided for identifying the minimum subset of tasks, tailoring the approach, executing iterative and incremental planning, and applying agile techniques, including support for managing projects using Scrum. Supplemental guidance provides specific support for Oracle products, such as UPK. OUM is available to Oracle employees, partners, and customers. Internal Use at Oracle: Employees can download OUM from MyDesktop. OUM Partner Program: OUM is available free of charge to Oracle PartnerNetwork (OPN) Diamond, Platinum, and Gold partners as a benefit of membership. These partners may download OUM from the Oracle Unified Method Knowledge Zone on OPN. OUM Customer Program: The OUM Customer Program allows customers to obtain copies of the method for their internal use by contracting with Oracle for a services engagement of two weeks or longer. Customers who have a signed contract with Oracle and meet the engagement qualification criteria as published on Customer tab of the OUM Website, are permitted to download the current release of OUM for their perpetual use. They may obtain subsequent releases published during a renewable, three-year access period To learn more about OUM, visit OUM Blog OUM on LinkedIn OUM on Twitter Emily Chorba, Principle Product Manager, Oracle User Productivity Kit

    Read the article

  • No input method choice appear on iBus

    - by phanect
    I've installed iBus and ibus-mozc, and an input method engine of Japanese from the repository, and attempted to enable mozc from Preference > "Input Method" tab > "Select Input Method" combo box. However, there is no choice to select, so I couldn't enable mozc. I also tried ibus-anthy, another legacy Japanese input method, but the situation was the same and I couldn't use anthy. Same problem is also occuring in openSUSE 12.1, so I don't think this is distribution-specific problem. In addition, this trouble also happened when I installed ibus-pynin, so this is not Japanese-specific. Any idea to find the cause of this trouble?

    Read the article

  • Default Parameters vs Method Overloading

    - by João Angelo
    With default parameters introduced in C# 4.0 one might be tempted to abandon the old approach of providing method overloads to simulate default parameters. However, you must take in consideration that both techniques are not interchangeable since they show different behaviors in certain scenarios. For me the most relevant difference is that default parameters are a compile time feature while method overloading is a runtime feature. To illustrate these concepts let’s take a look at a complete, although a bit long, example. What you need to retain from the example is that static method Foo uses method overloading while static method Bar uses C# 4.0 default parameters. static void CreateCallerAssembly(string name) { // Caller class - Invokes Example.Foo() and Example.Bar() string callerCode = String.Concat( "using System;", "public class Caller", "{", " public void Print()", " {", " Console.WriteLine(Example.Foo());", " Console.WriteLine(Example.Bar());", " }", "}"); var parameters = new CompilerParameters(new[] { "system.dll", "Common.dll" }, name); new CSharpCodeProvider().CompileAssemblyFromSource(parameters, callerCode); } static void Main() { // Example class - Foo uses overloading while Bar uses C# 4.0 default parameters string exampleCode = String.Concat( "using System;", "public class Example", "{{", " public static string Foo() {{ return Foo(\"{0}\"); }}", " public static string Foo(string key) {{ return \"FOO-\" + key; }}", " public static string Bar(string key = \"{0}\") {{ return \"BAR-\" + key; }}", "}}"); var compiler = new CSharpCodeProvider(); var parameters = new CompilerParameters(new[] { "system.dll" }, "Common.dll"); // Build Common.dll with default value of "V1" compiler.CompileAssemblyFromSource(parameters, String.Format(exampleCode, "V1")); // Caller1 built against Common.dll that uses a default of "V1" CreateCallerAssembly("Caller1.dll"); // Rebuild Common.dll with default value of "V2" compiler.CompileAssemblyFromSource(parameters, String.Format(exampleCode, "V2")); // Caller2 built against Common.dll that uses a default of "V2" CreateCallerAssembly("Caller2.dll"); dynamic caller1 = Assembly.LoadFrom("Caller1.dll").CreateInstance("Caller"); dynamic caller2 = Assembly.LoadFrom("Caller2.dll").CreateInstance("Caller"); Console.WriteLine("Caller1.dll:"); caller1.Print(); Console.WriteLine("Caller2.dll:"); caller2.Print(); } And if you run this code you will get the following output: // Caller1.dll: // FOO-V2 // BAR-V1 // Caller2.dll: // FOO-V2 // BAR-V2 You see that even though Caller1.dll runs against the current Common.dll assembly where method Bar defines a default value of “V2″ the output show us the default value defined at the time Caller1.dll compiled against the first version of Common.dll. This happens because the compiler will copy the current default value to each method call, much in the same way a constant value (const keyword) is copied to a calling assembly and changes to it’s value will only be reflected if you rebuild the calling assembly again. The use of default parameters is also discouraged by Microsoft in public API’s as stated in (CA1026: Default parameters should not be used) code analysis rule.

    Read the article

  • Method flags as arguments or as member variables?

    - by Martin
    I think the title "Method flags as arguments or as member variables?" may be suboptimal, but as I'm missing any better terminology atm., here goes: I'm currently trying to get my head around the problem of whether flags for a given class (private) method should be passed as function arguments or via member variable and/or whether there is some pattern or name that covers this aspect and/or whether this hints at some other design problems. By example (language could be C++, Java, C#, doesn't really matter IMHO): class Thingamajig { private ResultType DoInternalStuff(FlagType calcSelect) { ResultType res; for (... some loop condition ...) { ... if (calcSelect == typeA) { ... } else if (calcSelect == typeX) { ... } else if ... } ... return res; } private void InteralStuffInvoker(FlagType calcSelect) { ... DoInternalStuff(calcSelect); ... } public void DoThisStuff() { ... some code ... InternalStuffInvoker(typeA); ... some more code ... } public ResultType DoThatStuff() { ... some code ... ResultType x = DoInternalStuff(typeX); ... some more code ... further process x ... return x; } } What we see above is that the method InternalStuffInvoker takes an argument that is not used inside this function at all but is only forwarded to the other private method DoInternalStuff. (Where DoInternalStuffwill be used privately at other places in this class, e.g. in the DoThatStuff (public) method.) An alternative solution would be to add a member variable that carries this information: class Thingamajig { private ResultType DoInternalStuff() { ResultType res; for (... some loop condition ...) { ... if (m_calcSelect == typeA) { ... } ... } ... return res; } private void InteralStuffInvoker() { ... DoInternalStuff(); ... } public void DoThisStuff() { ... some code ... m_calcSelect = typeA; InternalStuffInvoker(); ... some more code ... } public ResultType DoThatStuff() { ... some code ... m_calcSelect = typeX; ResultType x = DoInternalStuff(); ... some more code ... further process x ... return x; } } Especially for deep call chains where the selector-flag for the inner method is selected outside, using a member variable can make the intermediate functions cleaner, as they don't need to carry a pass-through parameter. On the other hand, this member variable isn't really representing any object state (as it's neither set nor available outside), but is really a hidden additional argument for the "inner" private method. What are the pros and cons of each approach?

    Read the article

  • Why the R# Method Group Refactoring is Evil

    - by Liam McLennan
    The refactoring I’m talking about is recommended by resharper when it sees a lambda that consists entirely of a method call that is passed the object that is the parameter to the lambda. Here is an example: public class IWishIWasAScriptingLanguage { public void SoIWouldntNeedAllThisJunk() { (new List<int> {1, 2, 3, 4}).Select(n => IsEven(n)); } private bool IsEven(int number) { return number%2 == 0; } } When resharper gets to n => IsEven(n) it underlines the lambda with a green squiggly telling me that the code can be replaced with a method group. If I apply the refactoring the code becomes: public class IWishIWasAScriptingLanguage { public void SoIWouldntNeedAllThisJunk() { (new List<int> {1, 2, 3, 4}).Select(IsEven); } private bool IsEven(int number) { return number%2 == 0; } } The method group syntax implies that the lambda’s parameter is the same as the IsEven method’s parameter. So a readable, explicit syntax has been replaced with an obfuscated, implicit syntax. That is why the method group refactoring is evil.

    Read the article

  • Java's Object.wait method with nanoseconds: Is this a joke or am I missing something

    - by Krumia
    I was checking out the Java API source code (Java 8) just out of curiosity. And I found this in java/lang/Object.java. There are three methods named wait: public final native void wait(long timeout): This is the core of all wait methods, which has a native implementation. public final void wait(): Just calls wait(0). And then there is public final void wait(long timeout, int nanos). The JavaDoc for the particular method tells me that, This method is similar to the wait method of one argument, but it allows finer control over the amount of time to wait for a notification before giving up. The amount of real time, measured in nanoseconds, is given by: 1000000*timeout+nanos But this is how the methods achieves "finer control over the amount of time to wait": if (nanos >= 500000 || (nanos != 0 && timeout == 0)) { timeout++; } wait(timeout); So this method basically does a crude rounding up of nanoseconds to milliseconds. Not to mention that anything below 500000ns/0.5ms will be ignored. Is this piece of code bad/unnecessary code, or am I missing some unseen virtue of declaring this method, and it's no argument cousin as the way they are?

    Read the article

  • Fixing a spelling mistake in a method name

    - by One Two Three
    One of the methods that I commonly use in our codebase is misspelled (and it predated me). This really irritates me not simply because it is mispelled but more importantly it makes me ALWAYS get the method name wrong the first time I type it (and then I have to remember "Oh, right, it should be mispelled to this...") I'm making a few changes around the original method. Should I take the opportunity to just rename the freaking method?

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >