💡 𝗖# 𝐓𝐢𝐩 - 𝗗𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲𝘀 𝗕𝗲𝘁𝘄𝗲𝗲𝗻 𝗖𝗼𝗻𝘀𝘁 𝗮𝗻𝗱 𝗥𝗲𝗮𝗱𝗼𝗻𝗹𝘆 𝗞𝗲𝘆𝘄𝗼𝗿𝗱𝘀 🔥 𝗰𝗼𝗻𝘀𝘁 and 𝗿𝗲𝗮𝗱𝗼𝗻𝗹𝘆 in 𝗖# share the common feature of preventing variables from being modified after initialization, but they have some key differences. 🔷 𝗰𝗼𝗻𝘀𝘁 ➤ Constants are declared with the 𝗰𝗼𝗻𝘀𝘁 modifier. ➤ Defines a 𝗰𝗼𝗺𝗽𝗶𝗹𝗲-𝘁𝗶𝗺𝗲 constant. Its value is known and fixed at compile time and cannot be changed at runtime. ➤ Must be declared with an initializer and 𝗰𝗼𝗻𝘀𝘁 members are implicitly static. ➤ Can only be used with basic types like integers, booleans, and strings. User-defined types, including classes, structs, and arrays, cannot be 𝗰𝗼𝗻𝘀𝘁. 🔷 𝗿𝗲𝗮𝗱𝗼𝗻𝗹𝘆 ➤ Readonly are declared with the 𝗿𝗲𝗮𝗱𝗼𝗻𝗹𝘆 modifier. ➤ Defines a 𝗿𝘂𝗻𝘁𝗶𝗺𝗲 constant. Its value can be assigned during initialization or in the constructor, but cannot be modified after that. ➤ Can be declared with or without an initializer and can be static or non-static. ➤ Can be used with any type, including reference types. ❓What are your thoughts on 𝗰𝗼𝗻𝘀𝘁 and 𝗿𝗲𝗮𝗱𝗼𝗻𝗹𝘆? Comment below👇 ♻️ If this is useful, 𝙧𝙚𝙥𝙤𝙨𝙩 to spread the knowledge. 👉 Please follow me (Poorna Soysa) and click the notification bell icon (🔔)on my profile to receive notifications for all my upcoming posts. 𝗧𝗵𝗮𝗻𝗸 𝘆𝗼𝘂 𝗳𝗼𝗿 𝗿𝗲𝗮𝗱𝗶𝗻𝗴! #DotNET #CSharp #DotNETDevelopers #Programming
If you find this content valuable, a repost would greatly help get it to more people. Thank you ❤️
Insightful
Useful tip, thanks Poorna
Useful tips
Useful. Thanks Poorna Soysa
Useful tips
Thanks for sharing. A const is inlined by the compiler and theoretically offers better performance.
I always remember it using R for ReadOnly, R for Runtime. C for Constant, C for Compile time.
Tech Enthusiast | .NET | C# | Azure | AWS | SAP
3whttps://youtube.com/shorts/va5S8AZpPX0?feature=share