3

I am creating a string array with values from a custom object, like this:

foreach(MyObject o in MyObjectList)
    string[] myArray = new string[] {o.id, o.number.toString(), o.whatever, ...}

The problem here is, that any of those values can be NULL, which makes this code crash of course. Lets say o.number is NULL and the rest is not ... in this case I still want to fill the other values and put "NULL" as string instead of o.number.

Is there a nice way to do it, except checking each value?

Thanks :)

3
  • What about using Nullable type? Commented Feb 3, 2011 at 10:30
  • MyObject is defined, I cant change it...what happens if I called toString on a nullable type? Commented Feb 3, 2011 at 10:34
  • Nullable types work as their non-nullable base types for non-null values. Unfortunately, for null values it depends: if boxed, it throws a NullReferenceException since it's null, if strongly typed, it returns the empty string. Commented Feb 3, 2011 at 11:17

7 Answers 7

3

For projects where this is relevant I often define an Extension method ToStringOrNull as follows:

public static string ToStringOrNull(this object o) { 
    return o == null ? null : o.ToString();
}

To avoid intellisense pollution, if you happen to have a limited set of types for which such a ToStringOrNull is useful, you could (and I sometimes do) avoid adding the extension to object and instead copy-paste a bunch of copies for the relevant types. The function is easily written as a one-liner, so code-gen to work around this duplication is overkill.

Then, if you wish to replace string null with some placeholder text, use the null-coalescing operator.

e.g.

string[] myArray = new [] {
    o.id, o.number.ToStringOrNull(), o.whatever, ...
};// .Select(s=>s??"NULL").ToArray(); //uncomment to replace null with "NULL"
Sign up to request clarification or add additional context in comments.

Comments

3

You need to check each value, but it shouldn't be too bad using the ?? operator, so just need to do for each value:

o.id ?? "NULL"

1 Comment

o.id ?? "NULL" is okay, but not o.number.toString() if o.number is null, because you're calling the toString() function on a null pointer reference, which does not return null but throws an exception.
2

This is my suggestion.

Implement an extension method "AsString" this way:

namespace ConsoleApplication1
{
    public static class ObjectExtensions
    {
        public static string AsString(this object source)
        {
            if (source != null)
            {
                return source.ToString();
            }
            else
            {
                return null;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            object a = null;
            object b = "not null";

            string someText = a.AsString();
        }
    }
}

Now you can return the string if the whole reference has an object, or null, if the reference has no object.

2 Comments

It's a fine idea - but then, this is pretty much equivalent (but longer) to what I wrote.
Absoultely, I was writing the answer almost at the same time... Oops!
1

You just have to check the fields that can be null, like

foreach(MyObject o in MyObjectList)
  string[] myArray = new string[] {
    o.id,
    (o.number == null ? "NULL" : o.number.toString(),
    o.whatever, ... };

Comments

1

You'll have to check each value. A short way to do that would be something like:

string nullStr = "NULL";
foreach (MyObject o in MyObjectList) {
    string[] myArray = new string[] {
        o.id,
        (o.number ?? nullStr).ToString(),
        (o.whatever ?? nullStr).ToString(),
        ...
    };
}

Comments

0

If you want to only put non-null elements into your array, then you will need to check each value. There is no way around this.

Comments

0

I would go with one of these two options:

1.As others suggested implement an extension method for the types you want to check for null.

2.If you can't/don't want to use extension methods you could define a helper method in MyObject that would accept an object and basically do the same null checking.

string Check(object o)
{
    return o == null ? null : o.ToString(); 
}

Then you would wrap each property you want with this method call.

foreach(MyObject o in MyObjectList)
    string[] myArray = new string[] {o.id, o.Check(o.number), o.whatever, ...}

1 Comment

You could even make it a local variable: Func<object,string> stringize = o=>o==null?null:o.ToString();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.