Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. C# Convertion

C# Convertion

Scheduled Pinned Locked Moved C#
questioncsharphelp
13 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • OriginalGriffO OriginalGriff

    parths wrote:

    a.ToString would throw a null reference exception if a is null

    No, it doesn't! It will throw a NullReferenceException, since it has no instance to call a method from. Try it!

    The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

    P Offline
    P Offline
    parths
    wrote on last edited by
    #4

    I rechecked what I had typed. Isn't that what I had said? :)

    "It was when I found out I could make mistakes that I knew I was on to something." -Ornette Coleman "Philosophy is a study that lets us be unhappy more intelligently." -Anon.

    OriginalGriffO 1 Reply Last reply
    0
    • M Midnight Ahri

      I'm a bit confuse about C# convertion. What is the difference between three convertion below? txtValue = (string)a; txtValue = a.ToString(); txtValue = Convert.ToString(a); I appreciate any help. ;)

      OriginalGriffO Offline
      OriginalGriffO Offline
      OriginalGriff
      wrote on last edited by
      #5

      To add to (and correct) what parths said:

      parths wrote:

      a.ToString would throw a null reference exception if a is null

      No, it doesn't! It will throw a NullReferenceException, since it has no instance to call a method from. There is also:

      txtValue = a as string;

      Which will try to do a cast to a string, and return null if the cast cannot be performed instead of throwing an exception. This is frequently used when dealing with a variety of objects that derive from a single base class. For example:

      foreach (Control c in Controls)
      {
      Button b = c as Button;
      if ( b != null)
      {
      ...
      }
      }

      There is also an implicit call to ToString when you concatenate a strign with a non-string:

      int i = 999;
      string s = "The value is: " + i;

      Produces

      The value is: 999

      because the system does an implicit call to ToString to convert the data. You should also note that unless a class specifically implements ToString as an override, the default Object version will be called. This returns a string which contains the fully qualified name of the instance type, which catches a lot of people out, who assume that

      Image i = Image.FromFile(@"D:\Temp\MyPic.jpg");
      string s = i.ToString();
      string sql = "INSERT INTO MyTable (userPic) VALUES ('" + s + "')";
      ...

      will insert the image data into their database for later. What it actually inserts is the text

      System.Drawing.Bitmap

      which confuses them when it fails to work as a picture on retrieval. [edit]Spurious code block removed :O - Thanks Richard! - OriginalGriff[/edit]

      The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      L 1 Reply Last reply
      0
      • P parths

        I rechecked what I had typed. Isn't that what I had said? :)

        "It was when I found out I could make mistakes that I knew I was on to something." -Ornette Coleman "Philosophy is a study that lets us be unhappy more intelligently." -Anon.

        OriginalGriffO Offline
        OriginalGriffO Offline
        OriginalGriff
        wrote on last edited by
        #6

        Nice try - it almost worked... :laugh:

        The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

        P 1 Reply Last reply
        0
        • OriginalGriffO OriginalGriff

          Nice try - it almost worked... :laugh:

          The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

          P Offline
          P Offline
          parths
          wrote on last edited by
          #7

          I really hadn't hadn't got your point the first time around. Did you mean that saying 'a.ToString would throw an exception' should actually be 'Calling a.ToString would throw an exception'? Sounds like 2 very different things now that I think about it, although I had actually meant the latter. Thanks for correcting that. I hope I got it right this time.

          "It was when I found out I could make mistakes that I knew I was on to something." -Ornette Coleman "Philosophy is a study that lets us be unhappy more intelligently." -Anon.

          1 Reply Last reply
          0
          • P parths

            Midnight Ahri wrote:

            txtValue = (string)a;

            The typecast operation assumes that the object is of type or subclasses from the target type. So in the above statement a is assumes needs to have string in it's inheritance hierarchy You should try the above statement in your C# IDE. If 'a' is of type int or float (or anything non-string), the compiler throws an error since it would be a invalid typecast.

            Midnight Ahri wrote:

            txtValue = a.ToString();

            a.ToString call the ToString method that every class inherits from the System.Object[^] class. It does not typecast, it returns a new string representation. a.ToString would throw a null reference exception if a is null

            Midnight Ahri wrote:

            txtValue = Convert.ToString(a);

            Convert.ToString[^] returns String.Empty in case the object passed to it is null, otherwise it first checks for IConvertible and IFormattable ToString implementations in the object and uses them. Finally if those are it functions the same as the object's ToString.

            "It was when I found out I could make mistakes that I knew I was on to something." -Ornette Coleman "Philosophy is a study that lets us be unhappy more intelligently." -Anon.

            M Offline
            M Offline
            Midnight Ahri
            wrote on last edited by
            #8

            Thank you very much for the answer. It's really useful. :laugh:

            1 Reply Last reply
            0
            • M Midnight Ahri

              I'm a bit confuse about C# convertion. What is the difference between three convertion below? txtValue = (string)a; txtValue = a.ToString(); txtValue = Convert.ToString(a); I appreciate any help. ;)

              V Offline
              V Offline
              V 0
              wrote on last edited by
              #9

              just to complete the information. casting is often used in boxing/unboxing objects and is often an expensive operation. I didn't test, but I think that

              txtValue == (string)a;

              is a heavier operation than

              txtValue = a.ToString();

              with the additional problem that you get an exception if it cannot be cast. try/catch is also heavier then if/else. (so if(a != null) { txtValue = a.ToString() } is better than using try/catch. (this is what I call defensive programming) If you write your own class and override the ToString method, you can do some fancy stuff. eg. if you do NOT override, ToString will probably return something like "thenamespace.theclassname". If you do override it you can make a representation of your class like eg a JSON object or an XML string (or whatever format takes your fancy) with all property values in there. (serializing objects)

              txtValue = Convert.ToString(a);

              will convert the object to string, but in a safer way. In fact I rarely use the casting (option 1), only if I need to cast from a boxed object. I only use option 2 when I want to do fancy stuff with my class (because of the null reference exception problem.) I use option 3 in most normal cases. hope this helps.

              V.
              (MQOTD Rules and previous Solutions )

              1 Reply Last reply
              0
              • OriginalGriffO OriginalGriff

                To add to (and correct) what parths said:

                parths wrote:

                a.ToString would throw a null reference exception if a is null

                No, it doesn't! It will throw a NullReferenceException, since it has no instance to call a method from. There is also:

                txtValue = a as string;

                Which will try to do a cast to a string, and return null if the cast cannot be performed instead of throwing an exception. This is frequently used when dealing with a variety of objects that derive from a single base class. For example:

                foreach (Control c in Controls)
                {
                Button b = c as Button;
                if ( b != null)
                {
                ...
                }
                }

                There is also an implicit call to ToString when you concatenate a strign with a non-string:

                int i = 999;
                string s = "The value is: " + i;

                Produces

                The value is: 999

                because the system does an implicit call to ToString to convert the data. You should also note that unless a class specifically implements ToString as an override, the default Object version will be called. This returns a string which contains the fully qualified name of the instance type, which catches a lot of people out, who assume that

                Image i = Image.FromFile(@"D:\Temp\MyPic.jpg");
                string s = i.ToString();
                string sql = "INSERT INTO MyTable (userPic) VALUES ('" + s + "')";
                ...

                will insert the image data into their database for later. What it actually inserts is the text

                System.Drawing.Bitmap

                which confuses them when it fails to work as a picture on retrieval. [edit]Spurious code block removed :O - Thanks Richard! - OriginalGriff[/edit]

                The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #10

                OriginalGriff wrote:

                Produces

                <pre lang="text">

                Oops!

                Use the best guess

                OriginalGriffO 1 Reply Last reply
                0
                • L Lost User

                  OriginalGriff wrote:

                  Produces

                  <pre lang="text">

                  Oops!

                  Use the best guess

                  OriginalGriffO Offline
                  OriginalGriffO Offline
                  OriginalGriff
                  wrote on last edited by
                  #11

                  :O

                  The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

                  "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                  "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                  K 1 Reply Last reply
                  0
                  • OriginalGriffO OriginalGriff

                    :O

                    The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

                    K Offline
                    K Offline
                    Keith Barrow
                    wrote on last edited by
                    #12

                    n00b :)

                    “Education is not the piling on of learning, information, data, facts, skills, or abilities - that's training or instruction - but is rather making visible what is hidden as a seed”
                    “One of the greatest problems of our time is that many are schooled but few are educated”

                    Sir Thomas More (1478 – 1535)

                    1 Reply Last reply
                    0
                    • P parths

                      Midnight Ahri wrote:

                      txtValue = (string)a;

                      The typecast operation assumes that the object is of type or subclasses from the target type. So in the above statement a is assumes needs to have string in it's inheritance hierarchy You should try the above statement in your C# IDE. If 'a' is of type int or float (or anything non-string), the compiler throws an error since it would be a invalid typecast.

                      Midnight Ahri wrote:

                      txtValue = a.ToString();

                      a.ToString call the ToString method that every class inherits from the System.Object[^] class. It does not typecast, it returns a new string representation. a.ToString would throw a null reference exception if a is null

                      Midnight Ahri wrote:

                      txtValue = Convert.ToString(a);

                      Convert.ToString[^] returns String.Empty in case the object passed to it is null, otherwise it first checks for IConvertible and IFormattable ToString implementations in the object and uses them. Finally if those are it functions the same as the object's ToString.

                      "It was when I found out I could make mistakes that I knew I was on to something." -Ornette Coleman "Philosophy is a study that lets us be unhappy more intelligently." -Anon.

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #13

                      parths wrote:

                      The typecast operation assumes that the object is of type or subclasses from the target type.

                      Actually no, it could be that the (static) type of a has an explicit conversion to string.

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups