Question need clarity on Convert.Tostring

vkkishores

Member
Joined
Jan 5, 2023
Messages
8
Programming Experience
10+
hi

can any one help me why the below code is not working
C#:
class Program
{
    static void Main(string[] args)
    {
        int? id = null;

        string id1 = Convert.ToString(id).Trim();
        // id1 is getting "" value
        string fName=null;
        string FirstName = Convert.ToString(fName).Trim();

        //getting error

    }
}
 

Attachments

  • error.png
    error.png
    139.1 KB · Views: 12
Last edited by a moderator:
Solution
The overload of Convert.ToString that you're calling in the first instance is the one with a parameter of type object. Here's the implementation of that overload:
C#:
public static string ToString(Object value)
{
    return ToString(value, null);
}

public static string ToString(Object value, IFormatProvider provider)
{
    IConvertible ic = value as IConvertible;
    if (ic != null)
        return ic.ToString(provider);
    IFormattable formattable = value as IFormattable;
    if (formattable != null)
        return formattable.ToString(null, provider);
    return value == null ? String.Empty : value.ToString();
}
If you put that code into your own app and call that method directly then you can debug it and you'll see...
Please don't post unformatted code snippets. They are too hard to read.

Also, for future reference, please post error messages as text, formatted as quotes. Provide a screenshot if you think it adds value but code and error messages are text and should always be posted as such. We can't copy text from a picture.
 
The overload of Convert.ToString that you're calling in the first instance is the one with a parameter of type object. Here's the implementation of that overload:
C#:
public static string ToString(Object value)
{
    return ToString(value, null);
}

public static string ToString(Object value, IFormatProvider provider)
{
    IConvertible ic = value as IConvertible;
    if (ic != null)
        return ic.ToString(provider);
    IFormattable formattable = value as IFormattable;
    if (formattable != null)
        return formattable.ToString(null, provider);
    return value == null ? String.Empty : value.ToString();
}
If you put that code into your own app and call that method directly then you can debug it and you'll see that neither of the conditional casts succeed so you end up at the last return and you can see what that that will never return null but will return string.Empty if the parameter is null.

In the second case, the overload you're calling is this:
C#:
public static String ToString(String value)
{
    Contract.Ensures(Contract.Result<string>() == value);  // We were always skipping the null check here.
    return value;
}
As you can see, that simply returns whatever you passed in. If you pass null in the you get null out and if you call Trim on null then you get a NullReferenceException.
 
Solution
Thank you very much for the explanation. i have 2 questions,

1) what is the solution for the 2nd instance, i want to return "" if the datatype is a string, do i need to override the tostring() method?

2) could you please tell me from where you got the provided samples
 
Maybe you can use the null condition and null coalescing operators:
C#:
string FirstName = Convert.ToString(fName)?.Trim() ?? "";
?. prevents Trim to be called on null, ?? returns the other part if first part is null.

 
The bigger question though, is why are you calling ToString() on an object that you already know is a string.

Anyway, I would have approached more like:
C#:
string firstName = String.IsNullOrWhiteSpace(fname) ? "" : fname.Trim();
 
The bigger question though, is why are you calling ToString() on an object that you already know is a string.

Anyway, I would have approached more like:
C#:
string firstName = String.IsNullOrWhiteSpace(fname) ? "" : fname.Trim();
thanks for the reply , I dont like to use ternary operator or a if condition , instaed we can use convert.tostring that will handle null values , but now i understood that convert.tostring will not handle null values in a string .anyway thanks for correcting me
 
Your going to have a bit of a tough time coding if you strive to avoid conditional statements. I couldn't even write this post without dipping into one!
i am not against to write if conditions , i was in a impression that convert.tostring will handle the null values in a string variable
 
If Convert.ToString() acted like some other language implemtation where nulls are printed out as "(null)" instead of an empty string like you were expecting, would you still use it?
 
If Convert.ToString() acted like some other language implemtation where nulls are printed out as "(null)" instead of an empty string like you were expecting, would you still use it?
I will not use , if that is the case i would go for if else or ternary operator
 
Instead of using Convert.ToString, why not use the trusty .TryParse instead?
Old and Busted:
class Program
{
    static void Main(string[] args)
    {
        int? id = null;

        string id1 = Convert.ToString(id).Trim();
        // id1 is getting "" value
        string fName=null;
        string FirstName = Convert.ToString(fName).Trim();

        //getting error

    }
}


New Hotness:
class Program
{
    static void Main(string[] args)
    {
        int? id = null;
        string id1, fName, FirstName;
 
        if(Int.TryParse(id, out int someOtherID)){
         id1 = someOtherID.ToString(); //no need to trim it here.
        }

        //your three strings are already null, also, there's no need to do a convert on a string to a string...

    }
}
 
Back
Top Bottom