در انتهای نکتهی خروجی ref readonly عنوان شد که «در ابتدا قصد داشتند ref readonly را برای تعریف پارامترهای value type نیز بکار برند، اما این تصمیم با معرفی پارامترهای از نوع in جایگزین شد» اما ... مجددا به C# 12 اضافه شدهاست:
مثال زیر را درنظر بگیرید:
namespace CS8Tests; public class RefReadonlySample { public void Test() { var number = 5; Print(ref number); Console.WriteLine($"After Print -> Your number is {number}"); // Output: // Print -> Your number is 5 // After Print -> Your number is 6 } private void Print(ref int number) { Console.WriteLine($"Print -> Your number is {number}"); number++; } }
اگر بخواهیم از تغییرات پارامتر number در متد Print جلوگیری کنیم، میتوان از واژهی کلیدی in که در C# 7.2 ارائه شد، استفاده کرد:
private void Print(in int number)
error CS8331: Cannot assign to variable 'number' or use it as the right hand side of a ref assignment because it is a readonly variable
اکنون در C# 12 همین عمل را توسط واژههای کلیدی ref readonly نیز میتوان پیاده سازی کرد:
private void Print(ref readonly int number)
سؤال: چرا این تغییر در C# 12 رخ دادهاست، زمانیکه واژهی کلیدی in، دقیقا همین کار را انجام میداد؟
هدف، وضوح بیشتر API تولیدی و تاکید بر readonly بودن ارجاع دریافتی در این حالت و یکدستی قسمتهای مختلف زبان است.
همچنین واقعیت این است که یک چنین قابلیتهایی، استفادهی روزمرهای را در زبان #C ندارند و بیشتر هدف از وجود آنها، استفاده از API کتابخانههای C++/C در زبان #C است. برای مثال بجای اینکه تمام ارجاعات فقط خواندنی آنها را به پارامترهایی از نوع in تبدیل کنند (در کدهای قدیمی) که سبب بروز مشکلات عدم سازگاری میشود، اکنون میتوانند به سادگی refهای قدیمی تعریف شده را ref readonly کنند؛ بدون اینکه استفاده کنندگان با مشکلی مواجه شوند.