Skip to content
This repository has been archived by the owner on Mar 9, 2021. It is now read-only.

Struct's default constructor does not get called implicitly #381

Open
TriEdgeAIDeprecated opened this issue Feb 9, 2015 · 6 comments
Open

Comments

@TriEdgeAIDeprecated
Copy link

C# Code:

Vector3 vector;
vector.x = m00 * v.x + m10 * v.y + m20 * v.z + m30;

Generated JavaScript code:

var vector;
vector.x = this.m00 * v.x + this.m10 * v.y + this.m20 * v.z + this.m30;

Which results in an error, when running it. Instead it should be like so:

var vector = new $Vector3();
vector.x = this.m00 * v.x + this.m10 * v.y + this.m20 * v.z + this.m30;
@erik-kallen erik-kallen added the bug label Feb 9, 2015
@erik-kallen
Copy link
Contributor

When I try to compile a minimal sample using VS2012 I get a compilation error. Which setup are you using? If you're not using Visual Studio it's mono's responsibility to report this error, and perhaps it does not support that.

@TriEdgeAIDeprecated
Copy link
Author

I am using Visual Studio 2015 Preview. Try this code:

using System;
using System.Runtime.CompilerServices;

namespace Test
{
    [Mutable]
    struct Vector3
    {
        public float x;
        public float y;
    }

    class Program
    {
        static Vector3 GetIt()
        {
            Vector3 vector;
            vector.x = 5.0f;
            vector.y = 10.0f;
            return vector;
        }

        static void Main()
        {
            Vector3 vector = GetIt();
            Console.WriteLine(vector.x + ", " + vector.y);
        }
    }
}

As long as you initialize all fields of the returned struct within every possible code path in the function, it is OK not to explicitly call the constructor.

@erik-kallen
Copy link
Contributor

Ah, thank you!

@TriEdgeAIDeprecated
Copy link
Author

Another case:

Vector3[] arr = new Vector3[5];
arr[0].x = 0.0f; // error, arr[0] is undefined and has no member 'x', but that isn't how it should be

@erik-kallen
Copy link
Contributor

@TriEdgeAI That case is going to be very hard (impossible?) to fix. At least I have no idea of how to do it.

@TriEdgeAIDeprecated
Copy link
Author

I am not aware how the compiler works internally, but can't you generate an additional for-loop which initializes all elements to default(T), whenever new T[] is performed, such that T is value type?

@erik-kallen erik-kallen added this to the 3.0 milestone Apr 5, 2015
@erik-kallen erik-kallen self-assigned this Apr 5, 2015
@erik-kallen erik-kallen removed their assignment Apr 15, 2015
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants