Wiki

Ticket #377 (closed defect: invalid)

Opened 10 years ago

Last modified 10 years ago

Erroneous incompatible types when casting to enum

Reported by: Jonno Owned by:
Priority: minor Milestone:
Component: Cobra Compiler Version: 0.9.6
Keywords: Cc:

Description

It's very possible that I'm missing something obvious here, but I am getting an error on what appears to be a safe down-cast from Object? to (a subclass of) Enum?.

The specific method is Enum.parse, which is throwing the following error:

Incompatible types. Cannot assign value of type Object? on the right to TestEnum? on the left.

Full example:

enum TestEnum
    A, B, C

class PossibleEnumCompileIssue
    def main is shared
        # This doesn't work/compile:
        # x as TestEnum? = Enum.parse(TestEnum, 'A')

        # This works, though:
        y as TestEnum
        Enum.tryParse<of TestEnum>('A', out y)

        # I believe the first line should be equivalent to this?
        sharp'global::TestEnum z = (global::TestEnum) System.Enum.Parse(typeof(global::TestEnum), "A")'

The compiler rejects the cast even if I check the type of x before casting.

Change History

Changed 10 years ago by hopscc

Enum.parse returns Object? which cant be implicitly downcast/assigned to something more specific (like TestEnum? ).

you have to explicitly cast it

x as TestEnum? = Enum.parse(TestEnum, 'A') to TestEnum?

The non cast equivalence version is more like

 sharp'global::TestEnum z =  System.Enum.Parse(typeof(global::TestEnum), "A")'

The explicit casting fixes that up.

The templated version is 'wired' to the specific instantiated type from the template description ( it can only be TestEnum?) so a cast is unnecessary.

Changed 10 years ago by thriwkin

This works:

enum TestEnum
    A, B, C

class Program
    def main is shared
        x = Enum.parse(TestEnum, 'A') to TestEnum
            # Cobra translates this to C# like so:
			#     x = (TestEnum)(Enum.Parse(typeof(TestEnum), "A"));
        print x, x.getType

Changed 10 years ago by thriwkin

Sorry hopscc, I did not see your post

-- I forgott to click the "Reload" button of my browser.

You are a good Cobra teacher!

Changed 10 years ago by Jonno

  • status changed from new to closed
  • resolution set to invalid

Thank you! I had a feeling I'd overlooked something, sorry. Marking this as invalid.

Note: See TracTickets for help on using tickets.