Difference between const and static readonly keywords C#
If in your C# class you want to use a variable whose value will not change during the lifetime of that class, then you have
two options:
1. Use the "const" keyword: for e.g. public const int myVar = 100;
2. Use the "static readonly" keyword: for e.g. public static readonly int myVar = ConfigurationManager.AppSettings["value"];
The const variable has a limitation: it can ONLY be set during compile time. This means you cannot set its value using any code
logic, like getting its value from some config file, or from some "if" condition. Whereas the value of a static readonly field
can be set at run time, and can thus be modified by the containing class using any custom logic.
In the static readonly case, the containing class is allowed to modify it only
* in the variable declaration (through a variable initializer)
* in the static constructor (instance constructors, if it's not static)
Dotnet, DotnetCore, Azure, C#,VB.net, Sql Server, WCF, MVC ,Linq, Javascript and Jquery
Subscribe to:
Post Comments (Atom)
Implementing OAuth validation in a Web API
I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...
-
ViewBag, ViewData, TempData and View State in MVC ASP.NET MVC offers us three options ViewData, ViewBag and TempData for passing data from...
-
// Export Datatable to Excel in C# Windows application using System; using System.Data; using System.IO; using System.Windows.Forms; ...
No comments:
Post a Comment
Comments Welcome