Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cast to var #2827

Open
ekolis opened this issue Sep 26, 2019 · 5 comments
Open

Cast to var #2827

ekolis opened this issue Sep 26, 2019 · 5 comments

Comments

@ekolis
Copy link

ekolis commented Sep 26, 2019

This would be a shortcut for casting to the type of a variable - for instance

int x = 85;
object y = 42;
x = (var)y;

the cast would be equivalent to (int)y because x is of type int.

@alrz
Copy link
Member

alrz commented Sep 26, 2019

This looks like downcast and upcast (a static cast) from F#, both of which are target-typed.

For upcasting, it's recommended to use a helper method

T StaticCast<T, TDerived>(TDerived o) where TDerived : T => o;

But now you need to specify all type arguments. While partial type inference (#1349) could help with that, you could hide TDerived using a static class,

static class StaticCast<T> {
   static T From<TDerived>(TDerived o) where TDerived : T => o;
}

But once we have type inference from target-type (#92) you could use the original method with all type arguments inferred:

x = Cast(y); // Cast<int, object>(y)

which will work for upcasting as well.

@ronnygunawan
Copy link

Why not write it even shorter:

x = ()y;

for target-typed explicit cast.

@ekolis
Copy link
Author

ekolis commented Sep 27, 2019 via email

@ronnygunawan
Copy link

x = y; only works for upcast

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants
@ekolis @ronnygunawan @alrz and others