Create a string array and check for null values ​​in C #?

I am creating a string array with values ​​from a user object, for example:

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

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

Is there a good way to do this other than checking each value?

Thank:)

+3
source share
7 answers

For projects where this is relevant, I often define an extension method ToStringOrNullas follows:

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

intellisense, , ToStringOrNull , ( ) object - . , -, , .

, null -, .

.

string[] myArray = new [] {
    o.id, o.number.ToStringOrNull(), o.whatever, ...
};// .Select(s=>s??"NULL").ToArray(); //uncomment to replace null with "NULL"
+3

, , , :

o.id ?? "NULL"
+3

.

"AsString" :

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();
        }
    }
}

, null, .

+2

, ,

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

. , - :

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

, . .

0

:

1. , , null.

2. / , MyObject, .

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

, , .

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

Source: https://habr.com/ru/post/1789708/


All Articles