Hello Friends,
Good Morning, Afternoon, Evening what ever zone you are in. Myself Chakrapani Upadhyaya a Full Stack Engineer.
In this article we will look into the usage of const and readonly keywords.
Const:
Const are implicitly static and it must be initialized, that also compile time. If we declare const with initializing it e get error "A const field requires a value to be provided"
Const value cannot be changed or cannot be reinitialized.
As it is static we use a ClassName.ConstantName notation to access const variable.
public class Product { public const int MY_DISCOUNT_VALUE = 10; } public class UsingProduct { public int finalPrice = 100 * Product.MY_DISCOUNT_VALUE; }
ReadOnly:
We can declare read-only without initializing. But initialization should be done at run time within constructor only.
It is nothing like that we should do only run time, it allow us to provide value while declaration, but in constructor it will be overridden,
Once value is assigned within constructor, we cannot re-initialized the value again, i mean its done we should use that.
public class Product { public readonly double TaxAmt; public Product(string location) { if (location == "India") TaxAmt = 1.0; if (location == "USA") TaxAmt = 70.5; } } public static class UsingProduct { static Product productObj = new Product("India"); public static string GetFinalPrice() { return "Final Price is " + (productObj.TaxAmt + 100); } } namespace ReadOnlyAndConst { public class Program { public static void Main() { Console.WriteLine(UsingProduct.GetFinalPrice()); } } }
Output:
When to Use?
Its biggest question always, Answer is very simple.
Use const, if you are confident that the value of the constant won't change.
Use readonly, if you have a constant that may change or when you are in doubt
Simple Scenario:
I have Price Calculation based on tax amount, but the tax amount will be based on my location like India(1.0), USA(70.)
We get the value once object of the class invoked.
In this situation its better to use readonly
I hope you enjoyed this article.
That's it for right now, see you in next article until then take care bye bye 😄