简体   繁体   中英

Adding data to a generic string Array C#

I'm learning about generics in C#, and I'm trying to make a generic array and add some strings to it. I can easily add int values to it, but I can't figure out how to make it work with strings . When I'm trying to use strings I get NullReferenceException .

I have a class called myArray , and it looks like this:

class MyArray<T> : IComparable<T>, IEnumerable<T>, IEnumerator<T>
{
    T[] data = new T[10];
    int current = -1;

    public T[] Data
    {
        get { return data; }
    }

    public void Add(T value)
    {
        for (int i = 0; i < data.Length; i++)
        {
            if (data[i].Equals(default(T)))
            {
                data[i] = value;
                return;
            }
        }
        T[] tmp = new T[data.Length + 10];
        data.CopyTo(tmp, 0);
        Add(value);
    }

In my mainform I add the data like this:

class Program
{
    static void Main(string[] args)
    {
        MyArray<string> StringArray = new MyArray<string>();

        StringArray.Add("ONE");
        StringArray.Add("TWO");
    }
}

The default of string is null as it is a reference type, not a value type. You are constructing a new array of type T[] , which results in an array filled with the default value of T , which in this case is null .

Following that, data[i].Equals(default(T)) throws NRE as you are trying to call null.Equals(...) .

您的数组正在使用空值进行初始化,因此您在此行获得NRE:

if (data[i].Equals(default(T)))

if (data[i].Equals(default(T))) is where the issue lies. In a new string (or any other reference type) array,

var array = new String[10];

each element in the array is null by default. So when you say

data[i].Equals(default(T)

and data[i] is null , you're calling a method on a null reference, thus causing the exception to be thrown.

This doesn't happen for value types, as the array is initialized to the default value of whatever the value type is.

This is part of the problem with generics--you can't always treat reference types and value types the same.

Try this instead, to avoid default :

private int _currentIndex = 0;
public void Add(T value)
{
    data[_currentIndex] = value;
    _currentIndex++;
    if(_currentIndex == data.Length)
    {
       T[] tmp = new T[data.Length + 10];
        data.CopyTo(tmp, 0);
        data = tmp;
        _currentIndex = 0;
    }          
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM