0

Why the command line

vector3 NewPosition = (1,1,1);

is invalid? While the command line is valid

Vector3 NewPosition = new Vector3(1,1,1); 

why using the command line below, is accepted without using the word "new"? Isn't transform.position also containt 3 value of (x,y,z)?

Vector3 NewPosition = transform.position

By writing "Vector3 NewPosition" isn't that it already recognize "NewPosition" as a memory storage area for "Vector3" type data? just like int a=1? I'm quite lost in spotting the difference.

chuackt
  • 145
  • 5
  • 2
    With C# 9, you could have `Vector3 NewPosition = new (1,1,1);`, but that's probably as close as you'll get for now https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#target-typed-new-expressions – devNull Nov 16 '20 at 04:50

1 Answers1

2

In C# only certain types can be instantiated without using the new keyword by simply assigning a value to them.

  1. Most prominent are primitive types (e.g. int, float);
  2. Structs which provide public fields. (see this question, it also provides an explanation). In this case however you can only use the fields you assigned.

In those cases you are allowed to simply A) declare your variable, B) assign a value/some values for structs and C) use it afterwards.

public struct MyStruct
{
    public float X;
    public float Y;
    public float Z;
}

public class Usage
{
    public static void Test()
    {
        MyStruct myStruct;
        myStruct.X = 1;
        myStruct.Y = 2;
        Console.WriteLine(myStruct.X);
        Console.WriteLine(myStruct.Y);
        //Console.WriteLine(myStruct.Z); causes an error, since Z is still unassigned
    }
}

C# 9 makes the new keyword target-typed allowing to omit stating the obvious data type for creation.

List<string> myList = new();
// instead of
List<string> myList = new List<string>();
Thomas
  • 1,225
  • 7
  • 16