C# Convertion
-
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)
-
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. ;)
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 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.
Nice try - it almost worked... :laugh:
The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)
-
Nice try - it almost worked... :laugh:
The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)
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.
-
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.
Thank you very much for the answer. It's really useful. :laugh:
-
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. ;)
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.
-
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)
-
:O
The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)
-
:O
The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)
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)
-
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.