Home > Software engineering >  Is it possible to make a variable that can be an array or a non-array?
Is it possible to make a variable that can be an array or a non-array?

Time:06-29

I want to be able to do something like

public string[]|string stringsOrSingleString;

I want to create a variable that can be an array or a non-array of a specific type (a string in the example).

Example usage

I want to be able to do stringsOrSingleString = "bla" or stringsOrSingleString = new string[] { "bla" };

Do I need a custom class to do this? Preferably, I don't want to use a custom class, but if necessary then ok.

I should be able to tell later on if the value assigned was an array or non-array, using typeof or is, or something.

The whole reason for this ordeal is that I have a javascript API(that I didn't create), and I am trying to make a C# api that follows the JS api/syntax as close as possible.

Is this possible?

CodePudding user response:

May be you want something like this?

public class Item<T>
{
    public T Value => this.Values.Length > 0 ? this.Values[0] : default(T);

    public T[] Values { get; set; }
}

The class has an array of values and a single value. There are some implementations like this, for example, when you select files with OpenFileDialog: you have a list of files (for MultiSelect case) and also a single SelectedFile. My answer is focused with this in mind. If you need another thing, give more information.

UPDATE

You can update previous class in this way:

public class Item<T>
{
    public T Value => this.Values.Length > 0 ? this.Values[0] : default(T);

    public T[] Values { get; set; }

    public T this[int index] => this.Values[index];

    public static implicit operator Item<T>(T value)
    {
        return new Item<T> { Values = new[] { value } };
    }

    public static implicit operator Item<T>(List<T> values)
    {
        return new Item<T> { Values = values.ToArray() };
    }

    public static implicit operator Item<T>(T[] values)
    {
        return new Item<T> { Values = values };
    }
}

Example usage:

Item<string> item = "Item1";
string text = item.Value;
string sameText = item[0];

Item<string> items = new[] { "Item1", "Item2" };
string[] texts = item.Values;
string item1 = item[0];
string item2 = item[1];

You can create an instance using a simple object or an array. You can access to the first value using Value property and to all items using Values. Or use the indexer property to access to any item.

In C# you need to know the type of the variable. It's difficult work in the same form of JavaScript. They are very different languages.

  • Related