Posts

Showing posts from March, 2024

Read only vs Static vs Const

Const A variable declared as  const  must be assigned a value at declaration, and this value may not then change at a later time. public const string ConnectionString = "YourConnectionString" ; The value in a  const  variable is what's called a "compile-time" value, and is immutable (which means  it does not change over the life of the program ). Only  primitive or "built-in" C# types  (e.g. int, string, double) are allowed to be declared  const . Therefore, you cannot write either of these: public const DateTime DeclarationOfIndependence = new DateTime ( 1776 , 7 , 4 ) ; public const MyClass MyValue = new Class ( ) { Name = "TestName" } ; You want to use  const  when you have a variable whose value will not change, ever, during the time your application is being used. Further, any variable declared as  const  will also, implicitly, be declared  static . But that begs the question: what does  static...

Var vs Dynamic

The var keyword The var keyword was introduced in C# 3.0 and variables declared with var are statically typed. Here, the type of variable declared is decided at the compile time. Variables which are declared as var should be initialized at the time of declaration. By looking at the assigned value, the compiler will decide the variable type. As compiler knows the data type of the variable at compile time, errors will be caught at that time only.   Example var obj  "c-sharp corner" ;    In the above sentence, obj will be treated as a string  obj = 10;   In the above line, the compiler will throw an error, as compiler already decided the type of obj as String and assigned an integer value to string variable violating safety rule type.   The dynamic keyword The dynamic keyword was introduced in C# 4.0 and variables declared with dynamic were dynamically typed. Here, the type of variable declared is decided at runtime...

Async and Await in C#

The "async" keyword marks a method asynchronous, meaning it can be run in the background while another code executes. When you mark a method as async, you can use the "await" keyword to indicate that the method should wait for the result of an asynchronous operation before continuing. Use of 'async' and 'await' in C# Asynchronous programming is a programming technique that allows code to be executed concurrently without blocking the execution of the calling thread. In other words, asynchronous code can run in the background while other code is executing. In synchronous programming, each line of code is executed sequentially, and the program waits for each operation to complete before moving on to the next one. This can lead to performance problems, particularly in programs that need to perform long-running operations like I/O or network requests. Asynchronous programming allows programs to perform these operations without blocking the calling thread....