Avatar ·

What is the difference between const and readonly in C#? When to use which?

Hello everyone! I started learning C# and came across two modifiers that seem very similar to me: `const` and `readonly`. I understand that both make a variable immutable, but I feel there must be some fundamental difference between them that I'm missing. Here's a simple example I wrote: ```csharp public class MyClass { public const int MyConst = 10; public readonly int MyReadonly = 20; public MyClass() { MyReadonly = 30; // This works // MyConst = 40; // Error: constant cannot be changed } public void SomeMethod() { // MyReadonly = 50; // Error: readonly field can only be changed in constructor } } ``` I see that a `readonly` field can be changed in the constructor, while a `con