C#C
C#10mo ago
Faker

✅ readonly keyword vs const keyword and use-case

Hello guys, I just read a bit about the readonly keywords. From what I've read, using the
readonly
keyword, we can only assign a particular value to a variable either at declaration level or when using the constructor. In constrast with the const keyword, I think we can only assign a value to it in the declaration part.

I read that using const means the value is determined at compile-time itself while using readonly means value is determined at run-time.

My first question concerning the
readonly
keyword:

When we declare a property, consider the following:

C#
public struct Customer 
{ 
  
    public string Name { get; } 
    public int Price { get; } 
  
    // Readonly member 
    public readonly string Product { get; } 
  
    public Customer(string name, string product, int price) 
    { 
  
        this.Name = name; 
        this.Product = product; 
        this.Price = price; 
    } 
} 

My question is, if we omit the readonly keyword and just use { get; } without the set keyword, does the property behave as readonly?

Second question is, what are the use cases of readonly vs const keyword please
Was this page helpful?