Search Results

Search found 4591 results on 184 pages for 'tostring'.

Page 1/184 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Override ToString() in your Classes

    - by psheriff
    One of the reasons I love teaching is because of the questions that I get from attendees. I was giving a presentation at DevConnections and was showing a collection of Product objects. When I hovered over the variable that contained the collection, it looked like Figure 2. As you can see in the collection, I have actual product names of my videos from www.pdsa.com/videos being displayed. To get your data to appear in the data tips you must override the ToString() method in your class. To illustrate this, take the following simple Product class shown below: public class Product{  public string ProductName { get; set; }  public int ProductId { get; set; }} This class does not have an override of the ToString() method so if you create a collection of Product objects you will end up with data tips that look like Figure 1. Below is the code I used to create a collection of Product objects. I have shortened the code in this blog, but you can get the full source code for this sample by following the instructions at the bottom of this blog entry. List<Product> coll = new List<Product>();Product prod; prod = new Product()  { ProductName = "From Zero to HTML 5 in 60 Minutes",     ProductId = 1 };coll.Add(prod);prod = new Product()   { ProductName = "Architecting Applications …",     ProductId = 2 };coll.Add(prod);prod = new Product()  { ProductName = "Introduction to Windows Phone Development",    ProductId = 3 };coll.Add(prod);prod = new Product()   { ProductName = "Architecting a Business  …",     ProductId = 4 };coll.Add(prod);......   Figure 1: Class without overriding ToString() Now, go back to the Product class and add an override of the ToString() method as shown in the code listed below: public class Product{  public string ProductName { get; set; }  public int ProductId { get; set; }   public override string ToString()  {    return ProductName;  }} In this simple sample, I am just returning the ProductName property. However, you can create a whole string of information if you wish to display more data in your data tips. Just concatenate any properties you want from your class and return that string. When you now run the application and hover over the collection object you will now see something that looks like Figure 2. Figure 2: Overriding ToString() in your Class Another place the ToString() override comes in handy is if you forget to use a DisplayMemberPath in your ListBox or ComboBox. The ToString() method is called automatically when a class is bound to a list control. Summary You should always override the ToString() method in your classes as this will help you when debugging your application. Seeing relevant data immediately in the data tip without having to drill down one more layer and maybe scroll through a complete list of properties should help speed up your development process. NOTE: You can download the sample code for this article by visiting my website at http://www.pdsa.com/downloads. Select “Tips & Tricks”, then select “Override ToString” from the drop down list.  

    Read the article

  • which toString() method can be used performance wise??

    - by Mrityunjay
    hi, I am working on one project for performance enhancement. I had one doubt, while we are during a process, we tend to trace the current state of the DTO and entity used. So, for this we have included toString() method in all POJOs for the same. I have now implemented toString() in three different ways which are following :- public String toString() { return "POJO :" + this.class.getName() + " RollNo :" + this.rollNo + " Name :" + this.name; } public String toString() { StringBuffer buff = new StringBuffer("POJO :").append(this.class.getName()).append(" RollNo :").append(this.rollNo).append(" Name :").append(this.name); return buff.toString(); } public String toString() { StringBuilder builder = new StringBuilder("POJO :").append(this.class.getName()).append(" RollNo :").append(this.rollNo).append(" Name :").append(this.name); return builder .toString(); } can anyone please help me to find out which one is best and should be used for enhancing performance.

    Read the article

  • BigInteger.ToString() returns more than 50 decimal digits.

    - by brickner
    I'm using .NET 4 System.Numerics.BigInteger Structure and I'm getting results different from the documentation. In the documentation of BigInteger.ToString() Method It says: The ToString() method supports 50 decimal digits of precision. That is, if the BigInteger value has more than 50 digits, only the 50 most significant digits are preserved in the output string; all other digits are replaced with zeros. I have some code that takes a 60 decimal digits BigInteger and converts it to a string. The 60 significant decimal digits string didn't lose any significant digits: const string vString = "123456789012345678901234567890123456789012345678901234567890"; Assert.AreEqual(60, vString.Length); BigInteger v = BigInteger.Parse(vString); Assert.AreEqual(60, v.ToString().Length); Assert.AreEqual('9', v.ToString()[58]); Assert.AreEqual('1', v.ToString()[0]); Assert.AreEqual(vString, v.ToString()); All the asserts pass. What exactly does the quoted part of the documentation mean?

    Read the article

  • Auto-generating toString Method

    - by Gordon
    Is it good or bad practice auto-generating toString methods for some simple classes? I was thinking of generating something like bellow where it takes the variable names and produces a toString method that prints the name followed by it's value. private String name; private int age; private double height; public String toString(){ Formatter formatter = new Formatter(); return formatter.format("Name: %s, Age: %d, Height %f", name, age, height).toString(); }

    Read the article

  • convert ArrayList.toString() back to ArrayList in one call

    - by dotnetnewbie
    I have a toString() representation of an ArrayList. Copying the toString() value to clipboard, I want to copy it back into my IDE editor, and create the ArrayList instance in one line. In fact, what I'm really doing is this: my ArrayList.toString() has data I need to setup a unit test. I want to copy this ArrayList.toString() into my editor to build a test against this edge case I don't want to parse anything by hand My input looks like this: [15.82, 15.870000000000001, 15.92, 16.32, 16.32, 16.32, 16.32, 17.05, 17.05, 17.05, 17.05, 18.29, 18.29, 19.16] The following do not work: Arrays.asList() google collections Lists.newArrayList() Suggestions?

    Read the article

  • toString method for varargs contructor

    - by owca
    I have a varargs contructor like this : public class Sentence { public String[] str; public Sentence(Object... text){ StringBuilder sb = new StringBuilder(); for (Object o : text) { sb.append(o.toString()) .append(" "); } System.out.println(sb.toString()); } } Contructor can get various types of data (ints, strings, and Sentence objects as well). How to do a proper toString method for such class ?

    Read the article

  • Is ToString() optimized by compiler?

    - by TheVillageIdiot
    Suppose I've following Code: Console.WriteLine("Value1: " + SomeEnum.Value1.ToString() + "\r\nValue2: " + SomeOtherEnum.Value2.ToString()); Will Compiler Optimize this to: Console.WriteLine("Value1: " + SomeEnum.Value1 + "\r\nValue2: " + SomeOtherEnum.Value2); I've checked it with IL Disassembler and there are calls to IL_005a: callvirt instance string [mscorlib]System.Object::ToString() I don't know if JIT optimizes this.

    Read the article

  • document.getElementById in toString

    - by KooiInc
    edit Found my answers here. Bottom line: toString/valueOf can only return primitive types. So here the lack of native getters in javascript shows, I suppose. I would like to use the following simple function in an elementwrapper: function ElGetter(id){ var id = id; return { set: function(nwid){id = nwid;}, toString: function(){return document.getElementById(id);}, valueOf: function(){return document.getElementById(id);} }; } var myEl = ElGetter('myId'); console.log(myEl.innerHTML); //=> undefined But I can't get it to work. Is it a DOM/javascript restriction or am I missing something? Normally it works, as in: function Tester(){ var x = 1; return { toString: function(){return x}, valueOf: function(){return x} } } var myTest = Tester(); console.log(myTest); //=> 1

    Read the article

  • JavaScript using toString on a Function object to read text content

    - by mseeley
    Calling toString() on the function below returns different strings across browsers. I understand this is because ECMA-262 15.3.4.2 leaves wiggle room for each vendor. Chrome returns the comments in addition to all syntax. Sadly Firefox 3.6 omits the comments. Based on Firefox's behavior I haven't tested IE, Opera, or Safari. function foo() { /* comment */ var bar = true; } Specifically, I am attempting to embed meta data within a specially formatted comment block within a function. Later the return value of the functions toString() method would be parsed and values returned as an object. I've been unable to locate compatibility tables or alternatives to toString(). Does the community have any ideas? Btw, pre-processing JS files isn't an option. :( Thanks a lot. :)

    Read the article

  • Why Is ToString() Rounding My Double Value?

    - by user163757
    How do I prevent my double value from being rounded when converting to a string? I have tried both Convert.ToString and ToString() with the same result. For example my double may look something like 77.987654321, and the two strings conversions convert to to 77.98765. I need to keep the precision of the value as is.

    Read the article

  • java.util.Date.toString() is printing out wrong format

    - by pacoverflow
    The following code prints out "vmtDataOrig.creationdate=2012-11-03" VmtData vmtDataOrig = VmtDataDao.getInstance().loadVmt(1); System.out.println("vmtDataOrig.creationdate=" + vmtDataOrig.getCreationDate().toString()); Here is the definition of the creationDate field in the VmtData class: private Date creationDate = null; Here is the hibernate mapping of the creationDate field to the database table column: <property name="creationDate" column="CREATIONDATE" type="date"/> The CREATIONDATE column in the MySQL database table is of type "date", and for the record retrieved it has the value "2012-11-03". The Javadoc for the java.util.Date.toString() method says it is supposed to print the Date object in the form "dow mon dd hh:mm:ss zzz yyyy". Anyone know why it is printing it out in the form "yyyy-MM-dd"?

    Read the article

  • How to return a verbatim string from ConfigurationManager.AppSetting["settingname"].ToString()

    - by Josh H.
    I am using the ConfigurationManager.AppSetting["blah"].ToString() method to get the path to the folder that contains the files I'm needing. But I'm throwing an UnsupportedFormatException on the path when it tries to use Directory.GetFiles(path). The returning value has the escape characters included and I'm not sure how to keep it from returning the extra characters. This is what the path looks like after it is returned: \\\\\\\\C:\\\\folder1\\\\folder2

    Read the article

  • Why won't WPF databindings show text when ToString() has a collaborating object?

    - by Jay
    In a simple form, I bind to a number of different objects -- some go in listboxes; some in textblocks. A couple of these objects have collaborating objects upon which the ToString() method calls when doing its work -- typically a formatter of some kind. When I step through the code I see that when the databinding is being set up, ToString() is called the collaborating object is not null and returns the expected result when inspected in the debugger, the objects return the expected result from ToString() BUT the text does not show up in the form. The only common thread I see is that these use a collaborating object, whereas the other bindings that show up as expected simply work from properties and methods of the containing object. If this is confusing, here is the gist in code: public class ThisThingWorks { private SomeObject some_object; public ThisThingWorks(SomeObject s) { some_object = s; } public override string ToString() { return some_object.name; } } public class ThisDoesntWork { private Formatter formatter; private SomeObject some_object; public ThisDoesntWork(SomeObject o, Formatter f) { formatter = f; some_object = o; } public override string ToString() { return formatter.Format(some_object.name); } } Again, let me reiterate -- the ToString() method works in every other context -- but when I bind to the object in WPF and expect it to display the result of ToString(), I get nothing. Update: The issue seems to be what I see as a buggy behaviour in the TextBlock binding. If I bind the Text property to a property of the DataContext that is declared as an interface type, ToString() is never called. If I change the property declaration to an implementation of the interface, it works as expected. Other controls, like Label work fine when binding the Content property to a DataContext property declared as either the implementation or the interface. Because this is so far removed from the title and content of this question, I've created a new question here: http://stackoverflow.com/questions/2917878/why-doesnt-textblock-databinding-call-tostring-on-a-property-whose-compile-tim

    Read the article

  • What are the original reasons for ToString() in Java and .NET?

    - by d.
    I've used ToString() modestly in the past and I've found it very useful in many circumstances. However, my usage of this method would hardly justify to put this method in none other than System.Object. My wild guess is that, at some point during the work carried out and meetings held to come up with the initial design of the .NET framework, it was decided that it was necessary - or at least extremely useful - to include a ToString() method that would be implemented by everything in the .NET framework. Does anyone know what the exact reasons were? Am I missing a ton of situations where ToString() proves useful enough as to be part of System.Object? What were the original reasons for ToString()? Thanks a lot! PS - Again: I'm not questioning the method or implying that it's not useful, I'm just curious to know what makes it SO useful as to be placed in System.Object. Side note - Imagine this: AnyDotNetNativeClass someInitialObject = new AnyDotNetNativeClass([some constructor parameters]); AnyDotNetNativeClass initialObjectFullCopy = AnyDotNetNativeClass.FromString(someInitialObject.ToString()); Wouldn't this be cool? EDIT(1): (A) - Based on some answers, it seems that .NET languages inherited this from Java. So, I'm adding "Java" to the subject and to the tags as well. If someone knows the reasons why this was implemented in Java then please shed some light! (B) - Static hypothetical FromString vs Serialization: sure, but that's quite a different story, right?

    Read the article

  • Entities equals(), hashCode() and toString(). How to correctly implement them?

    - by spike07
    I'm implementing equals(), hashCode() and toString() of my entities using all the available fields in the bean. I'm getting some Lazy init Exception on the frontend when I try to compare the equality or when I print the obj state. That's because some list in the entity can be lazy initialized. I'm wondering what's the correct way to for implementing equals() and toString() on an entity object.

    Read the article

  • Entities equals() - hashcode() - toString(). How to correctly implement them?

    - by spike07
    I'm implementing equals() - hashcode() - toString() of my Entities using all the available fields in the bean. I'm getting some Lazy init Exception on the frontend when I try to compare the equality or when I print the obj state. That's because some list in the entity can be lazy initialized. I'm wondering what's the correct way to for implementing equals() and toString() on an Entity Obj

    Read the article

  • constructor function's object literal returns toString() method but no other method

    - by JohnMerlino
    I'm very confused with javascript methods defined in objects and the "this" keyword. In the below example, the toString() method is invoked when Mammal object instantiated: function Mammal(name){ this.name=name; this.toString = function(){ return '[Mammal "'+this.name+'"]'; } } var someAnimal = new Mammal('Mr. Biggles'); alert('someAnimal is '+someAnimal); Despite the fact that the toString() method is not invoked on the object someAnimal like this: alert('someAnimal is '+someAnimal.toString()); It still returns 'someAnimal is [Mammal "Mr. Biggles"]' . That doesn't make sense to me because the toString() function is not being called anywhere. Then to add even more confusion, if I change the toString() method to a method I make up such as random(): function Mammal(name){ this.name=name; this.random = function(){ return Math.floor(Math.random() * 15); } } var someAnimal = new Mammal('Mr. Biggles'); alert(someAnimal); It completely ignores the random method (despite the fact that it is defined the same way was the toString() method was) and returns: [object object] Another issue I'm having trouble understanding with inheritance is the value of "this". For example, in the below example function person(w,h){ width.width = w; width.height = h; } function man(w,h,s) { person.call(this, w, h); this.sex = s; } "this" keyword is being send to the person object clearly. However, does "this" refer to the subclass (man) or the super class (person) when the person object receives it? Thanks for clearing up any of the confusion I have with inheritance and object literals in javascript.

    Read the article

  • int.ToString like HH formatted of DateTime

    - by nCdy
    ("dd/MM/yyyy HH")+ " - " + (x.Hour+1).ToString(); So here is example what I got and what I need : 0 ---> 00 3 ---> 03 12 ---> 12 How can I use ToString for it ? I've tried : x.ToString("dd/MM/yyyy HH") + " - " + x.AddHours(1).ToString("HH"); doesn't works ...

    Read the article

  • replacing toString using Groovy metaprogramming

    - by Don
    In the following Groovy snippet, I attempt to replace both the hashCode and toString methods String.metaClass.toString = {-> "override" } String.metaClass.hashCode = {-> 22 } But when I test it out, only the replacement of hashCode works String s = "foo" println s.hashCode() // prints 22 println s.toString() // prints "foo" Is toString somehow a special case (possibly for security reasons)?

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >