Can you make a variable a constant after it had been created?

I have a variable which has a list of objects in it. It was made procedurally, with a loop in the start method. After that it will never be used again. I was wondering if there was a way to convert it to a constant after creation.

If you mean like a C# const variable. Then the short answer is no, once a variable is declared, you can’t change its type.

However, I guess it depends on what you want to achieve, though…

If you’re afraid that code outside the class might accidentally mutate the list content, then you could just expose a property that only allows iteration.

One example is:

public class Foo : MonoBehaviour {
    private List<int> randomStuff;
    public IEnumerable<int> RandomStuff => randomStuff;

    public Start() {
        randomStuff = // whatever
    }
}

I guess you could also explore other collection types, such as ImmutableList.

public class Foo : MonoBehaviour {
    public ImmutableList<int> RandomStuff { get; private set; }

    public Start() {
        List<int> randomStuff = // whatever
        RandomStuff = randomStuff.ToImmutableList();
    }
}

Of course something inside the class could still assign a new immutable list to the RandomStuff property, so still not completely bulletproof.