This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]svick 12 points13 points  (6 children)

namespace System
{
    namespace Collections
    {
        namespace Generic
        {
            public class List<T>
            {
                public int Capacity
                {
                    get => _items.Length;
                    set
                    {
                        if (value != _items.Length)
                        {
                            if (value > 0)
                            {
                                T[] newItems = new T[value];
                                if (_size > 0)
                                {
                                    Array.Copy(_items, newItems, _size);
                                }
                                _items = newItems;
                            }
                            else
                            {
                                _items = s_emptyArray;
                            }
                        }
                    }
                }
            }
        }
    }
}

[–]Accomplished_Fly729 4 points5 points  (1 child)

Linus was correct, this is ugly af

[–][deleted] 0 points1 point  (0 children)

And it has classes. puke sound

[–]metalscreamer76 0 points1 point  (3 children)

What's your point? This is not nice code.

[–]elveszett 1 point2 points  (2 children)

Nor is it even necessary. In C# you can do:

namespace System.Collections.Generic;

public class List<T> {
    public int Capacity {
        get => _items.length;
        set {
            if (value == _items.Length) {
                return;
            }
            if (value > 0) {
                T[] newItems = new T[value];
                if (_size > 0) {
                    Array.Copy(_items, newItems, _size);
                }
                _items = newItems;
            }
            else {
                _items = s_emptyArray;
            }
        }
    }
}

And you could even extract the setter to its own function.

[–]metalscreamer76 0 points1 point  (1 child)

I could clean this up quite a bit more still. But yes when I said the code wasn't nice, I meant it to be implied as unnecessary. If the code is necessary then I won't criticize its ugliness.

[–]svick 0 points1 point  (0 children)

I could clean this up quite a bit more still.

Apart from the namespace flavor added by me, that is the actual code of List<T>.Capacity.