-
Notifications
You must be signed in to change notification settings - Fork 4.1k
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
Support the use of var in more cases #2114
Comments
The example you provide can be easily simplified with the use of the ?: operator. var query = from p in Context.Query<Person>
select SimpleQuery ?
new PersonViewModel { Person = p } :
new PersonViewModel { Person = p, Friends = p.Friends }; That said there are cases where it could be useful, such as in try - catch - finally blocks, but it would have some unpleasant consequences. For instance, the type of the variable cannot be referred to until it has been assigned. Also, the type becomes path dependent so the compiler would need to do flow analysis to make sure that all possible assignments resolve to the same type. |
Yeah - the example was certainly the most simple version and could be replaced with ?:, but you can imagine much more complex versions, try/catch as you mentioned, usings, multiple ifs, switch statements, etc. Why couldn't the type of the variable be referred to? The variable isn't dynamic - it would still be statically known through some compiler magic ;) -- hopefully only needing limited flow analysis over what is currently done for var. And any case the compiler didn't want to support (because of complexity or whatnot) it could just issue an error that var couldn't be used in that case. While I think the simple var case is nice, my guess the bang for the buck wouldn't necessarily pay off (but wanted to raise it as it would be nice and who knows might be easy). Though I think the really valuable feature would be "structural" typing with anonymous objects. That imo would be a huge win and isn't just syntactical sugar. |
To your first point: To your second point: To your third point: |
You can't use fixed (var* ptr = "abc")
{
ptr[0] = 'A';
} |
Also consider |
Issue moved to dotnet/csharplang #520 via ZenHub |
Currently
var
can only be used in cases where the declaration and assignment are linked. It would be great (imo) ifvar
could be used even if those statements weren't linked but was still verifiable by the compiler (not looking for dynamic here or anything like that).This would be great for cases like the following silly example:
Before:
After:
It would be even more awesome if the compiler could infer even more - maybe using some structural typing when generating the anonymous, like:
The text was updated successfully, but these errors were encountered: