Cloning arrays : Array Clone « Data Structure « C# / CSharp Tutorial






using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

class GoodMonthType {
    private static readonly string[] monthConstants = new string[] {
        "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
    };

    public string[] Months
    {
        get { return (string[])monthConstants.Clone(); }
    }

    public IEnumerable<string> MonthsEnumerable
    {
        get { return Array.AsReadOnly<string>(monthConstants); }
    }
}

public class MainClass
{

    public static void Main()
    {
        GoodMonthType mt2 = new GoodMonthType();
        
        foreach (string m in mt2.Months) {
            Console.WriteLine(m);
        }
        string[] months2 = mt2.Months;
        months2[3] = "Not-April";

        foreach (string m in mt2.Months) {
            Console.WriteLine(m);
        }
    }
}
January
February
March
April
May
June
July
August
September
October
November
December
January
February
March
April
May
June
July
August
September
October
November
December








11.11.Array Clone
11.11.1.Clone array with reference data inside
11.11.2.Clone Value Array
11.11.3.Cloning arrays