'?' afterClasses and Classes in parentheses

Hi everyone,

Been watching some Youtube videos about learning how to prog in Unity and C#. Got some questions and couldn’t Google answers, because I hadn’t found how to question it properly.

        public static TextMesh CreateWorldText(string text, Transform parent = null, Vector3 localPosition = default(Vector3), int fontSize = 40, Color? color = null, TextAnchor textAnchor = TextAnchor.UpperLeft, TextAlignment textAlignment = TextAlignment.Left, int sortingOrder = sortingOrderDefault) {
            if (color == null) color = Color.white;
            return CreateWorldText(parent, text, localPosition, fontSize, (Color)color, textAnchor, textAlignment, sortingOrder);
        }

Could you explain, please:

  1. What is ‘?’ operator after Color class? Is it regular conditional operator? Than why it doesn’t have consequent : alternative? And why it equals something?

I tried to find it out in the C# docs, but I’ve failed :slight_smile: Maybe didn’t look close enough.

  1. Why class Color in return type parameters is in parentheses? What does that mean? Removing parentheses gives a syntax error with color varuable. And removing the whole ‘(Color)’ gives an error with ‘parent’ and ‘text’ (can’t convert to string and transform accordingly)

Sorry for grammar and noob questions :slight_smile:

Would be gratefull for any explanations or docs.

“What is ‘?’ operator after Color class?”

See this page:

“Why class Color in return type parameters is in parentheses?”

(Color)color

This casts nullable type variable to Color type. IIRC those are two different things.

See this page:

3 Likes

This question mark operator is confusing because:

  1. ? is hard to google

  2. ? has at least THREE (3) completely-unrelated uses.

For instance, here is the first use:

If you declare a variable:

int foo;

That’s an integer. If you declare it this way:

int? foo;

That is a nullable integer. Integers cannot normally be null, but an int? can be.

That is the use in your example above. Since Color can’t be null, Color? actually CAN be null.

The second use is the ternary operator, a shortcut for “if else” that can be combined into a result:

result = condition ? ifTrue : ifFalse;

That assigns either ifTrue to result or ifFalse to result, based on the boolean condition

The third and newest use is the null coalesce operator, which is NOT good to use in Unity because of the UnityEngine.Object null test equality overload.

result = myObject?.dataField;

This will conditionally check if myObject is null, and if it is non-null, it will dereference .dataField and assign it to result.

Do NOT use the third version in Unity unless you know what you’re doing. Instead, write the above as:

if (myObject != null)
{
  result = myObject.dataField;
}

That will always work.

5 Likes

Thanks a lot both of you

1 Like