4

C# Language Highlights: The "in" Parameter Modifier | On .NET | Channe...

 3 years ago
source link: https://channel9.msdn.com/Shows/On-NET/C-Language-Highlights-The-in-Parameter-Modifier?WT_mc_id=DOP-MVP-4025064
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

The Discussion

DotnetSql​Coder

Why didnt they reuse the readonly keyword , would have been suited better in that situation ? Would have made the code more readable .

ABJ

https://channel9.msdn.com/Shows/On-NET/C-Language-Highlights-The-in-Parameter-Modifier

ABJ

Sorry about the earlier message, bad case of mobile copy/pasting.

Anyway, unless I'm mistaken, that video completely misses the point of that keyword, as it was not created for the purpose of preventing the reuse of a parameter variable within a method (otherwise people are going to think they should put it nearly everywhere).
If you remove the 'in' keyword as you did in the video, it doesn't change anything for the caller. Reassigning the 'input' parameter within the Print() method doesn't change the values held by the 'person' or 'number' variables in Main().
If you were using the 'ref' keyword though, it would. But if you didn't want your variables to be affected, then using 'ref' with a reference type such as Object wouldn't make sense! It would instead make sense to use 'ref' with value types (struct) for performance reasons, to avoid the copying of data that passing by value incurs. And that's where 'in' is useful, because you can now get that performance benefit of 'ref' without risking the called method changing your variables.
So basically for your example to have made sense, you should have changed the type of 'input' to a value type such as int, or made the Print() method generic with a constraint of struct for the type parameter (so bye bye record). And you should at least have mentioned that the main purpose of that keyword was for performance with value types.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK