Remove last element of array in C#

March 25, 2014 0 Comments

Using the Resize method you can decrement size of an array. Resize method creates a new array with new specified size Also copy old array items into newly created. Let's take an simple example to remove last element. Take less than one size of original array size. Newly created array skip last element of original array size.

<form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" Height="37px" onclick="Button1_Click"
        Text="Vegetable" Width="100px" />
        <asp:Label ID="Label1" runat="server" Text="Label" Width="100px" ForeColor="Black" BackColor="Yellow"></asp:Label>

Business Logic code

 protected void Button1_Click(object sender, EventArgs e)
        string[] Vegtables = new string[]

        Label1.Text = "Vegtables array...<br />";
        foreach (string Vegtable in Vegtables)
            Label1.Text += Vegtable + "<br />";

        Array.Resize(ref Vegtables, Vegtables.Length - 1);

        Label1.Text += "<br />Vegtables array [last element remove...<br />";
        foreach (string Vegtable in Vegtables)
            Label1.Text += Vegtable + "<br />";

Code Generate the following Output

Resize array method

Jackrin Reacher

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google