Return an empty array instead of null

I created a class Settingsthat I use to edit my application in a file .ini. My file is Settings.inias follows:

[ACCOUNT]
login=xyz
password=xyz
locations=1,2,5,8

Now I get the following values:

class Settings {
    public static IniFile Config = new IniFile(Directory.GetCurrentDirectory() + @"\Settings.ini");
    public static string Login { get { return Config.Read("login", "ACCOUNT"); } set { Config.Write("login", "ACCOUNT"); } }
    public static string Password { get { return Config.Read("password", "ACCOUNT"); } set { Config.Write("password", "ACCOUNT"); } }
    public static int[] Locations { get { return Array.ConvertAll(Config.Read("locations", "ACCOUNT").Split(','), s => int.Parse(s)); } set { Config.Write("locations", "ACCOUNT"); } }
}

The problem is that my file Settings.inihas empty spaces:

locations=

My variable Settings.Locationsreturns nullinstead of an empty array. I tried to do something like this:

public static int[] Locations 
{ 
    get { return new int[] {Array.ConvertAll(Config.Read("locations", "ACCOUNT").Split(','), s => int.Parse(s))}; } 
    set { Config.Write("locations", "ACCOUNT"); } 
}

But that just doesn't work. I cannot convert int [] to int. Do you have any idea how I can return an empty array?

+4
source share
2 answers

You can do it explicitly:

public static int[] Locations
{
    get
    {
        string locations = Config.Read("locations", "ACCOUNT");
        if (locations == null)
        {
            return new int[0];
        }
        return locations
                .Split(',')         // split the locations separated by a comma
                .Select(int.Parse)  // transform each string into the corresponding integer
                .ToArray();         // put the resulting sequence (IEnumerable<int>) into an array of integers
    }
    set
    {
        Config.Write("locations", "ACCOUNT");
    }
}
+9
source

, , , . - :

public static int[] Locations 
{ 
    get 
    { 
        int[] values = Array.ConvertAll(Config.Read("locations", "ACCOUNT").Split(','), 
            s => int.Parse(s)) ?? new int[] { };
        return values; 
    } 
    set 
    { 
        Config.Write("locations", "ACCOUNT"); 
    } 
}

, ?? new int[] { } , . , null.

, , , - , , , . Locals.

+5

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


All Articles