0

I have a very simple class that wont compile because of a default parameter in the constructor. The language is C# and the class will be used in a Unity3d game. So this compile error is occurring in Unity's "IDE"

Compile Error:

Assets/Utilities/GenericClasses.cs(30,94): error CS1736: The expression being assigned to optional parameter `nName' must be a constant or default value

public class Element {
    public static readonly string NULL_NAME = "___NULL_NAME___";
    public enum elementType {E_ELEMENT, E_MODEL, E_VIEW, E_SUPER, E_ARC};
    private string name;
    private elementType type;

    // line 30 is below
    public Element(elementType nType=elementType.E_ELEMENT, string nName=NULL_NAME) {
        type = nType;
        name = nName;
    }
}

What am I doing wrong?

3 Answers 3

1

You should use a constant value instead of a static readonly:

public const string NULL_NAME = "___NULL_NAME___";

The reason why your code doesn't compile is because you attempted to assign a non constant default value to the nName parameter in the constructor which is not supported.

Sign up to request clarification or add additional context in comments.

Comments

1

NULL_NAME is not a constant, it is readonly.

A readonly variable can be initialized in the constructor so it is not known at compile time which is required for a default value for an optional parameter because the compiler will substitute the value where it is omitted in a call.

Comments

0

Try this one

public const string NULL_NAME = "___NULL_NAME___";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.