[c#] How to do ToString for a possibly null object?

Is there a simple way of doing the following:

String s = myObj == null ? "" : myObj.ToString();

I know I can do the following, but I really consider it as a hack:

String s = "" + myObj;

It would be great if Convert.ToString() had a proper overload for this.

This question is related to c# .net string object null

The answer is


string.Format("{0}", myObj);

string.Format will format null as an empty string and call ToString() on non-null objects. As I understand it, this is what you were looking for.


I disagree with that this:

String s = myObj == null ? "" : myObj.ToString();

is a hack in any way. I think it's a good example of clear code. It's absolutely obvious what you want to achieve and that you're expecting null.

UPDATE:

I see now that you were not saying that this was a hack. But it's implied in the question that you think this way is not the way to go. In my mind it's definitely the clearest solution.


Even though this is an old question and the OP asked for C# I would like to share a VB.Net solution for those, who work with VB.Net rather than C#:

Dim myObj As Object = Nothing
Dim s As String = If(myObj, "").ToString()

myObj = 42
s = If(myObj, "").ToString()

Unfortunatly VB.Net doesn't allow the ?-operator after a variable so myObj?.ToString isn't valid (at least not in .Net 4.5, which I used for testing the solution). Instead I use the If to return an empty string in case myObj ist Nothing. So the first Tostring-Call return an an empty string, while the second (where myObj is not Nothing) returns "42".


With an extension method, you can accomplish this:

public static class Extension
{
    public static string ToStringOrEmpty(this Object value)
    {
        return value == null ? "" : value.ToString();
    }
}

The following would write nothing to the screen and would not thrown an exception:

        string value = null;

        Console.WriteLine(value.ToStringOrEmpty());

It would be great if Convert.ToString() had a proper overload for this.

There's been a Convert.ToString(Object value) since .Net 2.0 (approx. 5 years before this Q was asked), which appears to do exactly what you want:

http://msdn.microsoft.com/en-us/library/astxcyeh(v=vs.80).aspx

Am I missing/misinterpreting something really obvious here?


string s = String.Concat(myObj);

would be the shortest way I guess and also have neglible performance overhead. Keep in mind though it wouldn't be quite clear for the reader of the code what the intention is.


I might get beat up for my answer but here goes anyway:

I would simply write

string s = ""
if (myObj != null) {
   x = myObj.toString();
}

Is there a payoff in terms of performance for using the ternary operator? I don't know off the top of my head.

And clearly, as someone above mentioned, you can put this behavior into a method such as safeString(myObj) that allows for reuse.


actually I didnt understand what do you want to do. As I understand, you can write this code another way like this. Are you asking this or not? Can you explain more?

string s = string.Empty;
    if(!string.IsNullOrEmpty(myObj))
    {
    s = myObj.ToString();
    }

I had the same problem and solved it by simply casting the object to string. This works for null objects too because strings can be nulls. Unless you absolutely don't want to have a null string, this should work just fine:

string myStr = (string)myObj; // string in a object disguise or a null

Some (speed) performance tests summarizing the various options, not that it really matters #microoptimization (using a linqpad extension)

Options

void Main()
{
    object objValue = null;
    test(objValue);
    string strValue = null;
    test(strValue);
}

// Define other methods and classes here
void test(string value) {
    new Perf<string> {
        { "coallesce", n => (value ?? string.Empty).ToString() },
        { "nullcheck", n => value == null ? string.Empty : value.ToString() },
        { "str.Format", n => string.Format("{0}", value) },
        { "str.Concat", n => string.Concat(value) },
        { "string +", n => "" + value },
        { "Convert", n => Convert.ToString(value) },
    }.Vs();
}

void test(object value) {
    new Perf<string> {
        { "coallesce", n => (value ?? string.Empty).ToString() },
        { "nullcheck", n => value == null ? string.Empty : value.ToString() },
        { "str.Format", n => string.Format("{0}", value) },
        { "str.Concat", n => string.Concat(value) },
        { "string +", n => "" + value },
        { "Convert", n => Convert.ToString(value) },
    }.Vs();
}

Probably important to point out that Convert.ToString(...) will retain a null string.

Results

Object

  • nullcheck 1.00x 1221 ticks elapsed (0.1221 ms) [in 10K reps, 1.221E-05 ms per]
  • coallesce 1.14x 1387 ticks elapsed (0.1387 ms) [in 10K reps, 1.387E-05 ms per]
  • string + 1.16x 1415 ticks elapsed (0.1415 ms) [in 10K reps, 1.415E-05 ms per]
  • str.Concat 1.16x 1420 ticks elapsed (0.142 ms) [in 10K reps, 1.42E-05 ms per]
  • Convert 1.58x 1931 ticks elapsed (0.1931 ms) [in 10K reps, 1.931E-05 ms per]
  • str.Format 5.45x 6655 ticks elapsed (0.6655 ms) [in 10K reps, 6.655E-05 ms per]

String

  • nullcheck 1.00x 1190 ticks elapsed (0.119 ms) [in 10K reps, 1.19E-05 ms per]
  • Convert 1.01x 1200 ticks elapsed (0.12 ms) [in 10K reps, 1.2E-05 ms per]
  • string + 1.04x 1239 ticks elapsed (0.1239 ms) [in 10K reps, 1.239E-05 ms per]
  • coallesce 1.20x 1423 ticks elapsed (0.1423 ms) [in 10K reps, 1.423E-05 ms per]
  • str.Concat 4.57x 5444 ticks elapsed (0.5444 ms) [in 10K reps, 5.444E-05 ms per]
  • str.Format 5.67x 6750 ticks elapsed (0.675 ms) [in 10K reps, 6.75E-05 ms per]

Holstebroe's comment would be your best answer:

string s = string.Format("{0}", myObj);

If myObj is null, Format places an Empty String value there.

It also satisfies your one line requirement and is easy to read.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to null

getElementById in React Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? How to resolve TypeError: Cannot convert undefined or null to object Check if returned value is not null and if so assign it, in one line, with one method call How do I assign a null value to a variable in PowerShell? Using COALESCE to handle NULL values in PostgreSQL How to check a Long for null in java Check if AJAX response data is empty/blank/null/undefined/0 Best way to check for "empty or null value"