Top 50 C# Interview Questions And Answers For Freshers And Experienced In 2022

This post includes the top 50 C# interview questions and answers for freshers and experienced professionals. This article will assist you in improving your C# knowledge and evaluating your present C# understanding.

Top-50-C#-Interview-Questions-Answers
Top-50-C#-Interview-Questions-Answers

Table of Contents

C# Basic Interview Questions and Answers

1. What is C#?

C# (pronounced “See Sharp”) is a modern, object-oriented, and type-safe programming language developed by Microsoft in the year 2000. C# enables developers to build many types of secure and robust applications including Windows apps, Web apps, Mobile (native iOS and Android apps), Web services, blockchain applications, Artificial intelligence (AI), and machine learning software.
The most recent version of C# is V10.0, which was introduced with Visual Studio 2022. A comprehensive series on C# 10 may be found here: C# 10 new features

2. What is class in C#?

In C#, a class is a user-defined data type that contains constructors, fields, properties, methods, events, delegates, indexers, and other data members. It’s a placeholder that lets you specify variables of different data types and methods in a single unit.
A class is a template or prototype for a group of objects that have similar properties and behaviors, while an object is a class instance.
In C #, classes are reference types that are stored in heap memory.
A class in C# can have as many objects as needed.

For example, Hyundai Creta is an instance of Car class, and the brand, model, color, speed are its properties.

Example of Class in C#

To create a class, use the class keyword, followed by the class name and a set of curly brackets {} around the body.

using System;
namespace ClassExample
{
    // Creating class of Car type
    public class Car
    {
        // Data  members (Fields) of a class
        public string brand;
        public string modal;
        public string color;
        public int topSpeed;

        // Constructor
        public Car(string brand, string modal, string color, int topSpeed)
        {
            this.brand = brand;
            this.modal = modal;
            this.color = color;
            this.topSpeed = topSpeed;
            
        }

        // Method
        public void CarDetails()
        {
         Console.WriteLine($"Brand: {brand}, Modal: {modal}, Color: {color}, Speed: {topSpeed}");
        }
        
    }

    class Program
    {
        static void Main(string[] args)
        {   
            // Creating instance 'HyundaiCreta' of Car class.
            Car HyundaiCreta = new Car("Hyundai", "Creta", "Red", 165);
                HyundaiCreta.CarDetails();
        }
    }

    // Output:
    // Brand: Hyundai, Modal: Creta, Color: Red, Speed: 165
}

To read more about OOPs, check out this article: C# OOPs Concept

3. What is the difference between a struct and a class in C#?

The Struct and Class are user-defined data types that can contain data members of different data types in a single unit. The following are the main difference between the struct and class in C#.

    • Struct is a value type inherited from System.ValueType whereas Class is a reference type inherited from System.Object class.
    • Classes are stored in heap memory, whereas structs are stored on the stack.
    • A class can inherit from another class, but a struct cannot inherit from another struct or class except interfaces.
    • The structure is implicitly sealed and cannot be a base class, whereas the class can be a base class.
    • By default, class members are private, whereas struct members are public.

To read more, check out this article: C# Struct vs Class

4. what is constructor and its types in C#

A Constructor is a special method that gets executed when an instance of the class or struct is created. The constructor is used to initialize and set default values for the data members of the new object. Its name is the same as the class or structure.
If we create a class without a constructor, the compiler will automatically create a default constructor for that class. Each class required at least one constructor.
The default constructor is used to set all the numeric variables in a class to zero, and all string fields and objects are set to null If no value is assigned.

The following are 5 types of constructors available in C#.

    • Default Constructor
    • Parameterized Constructor
    • Copy Constructor
    • Static Constructor
    • Private Constructor

To read more, check out this article: Types of constructors in C#

5. What is destructor in C#?

A destructor is a class member function that is called automatically to destroy objects of class when the scope of an object ends. A class can only have one destructor, which must be preceded by a tilde (~) and has the same name as the class.
In C# destructor, parameters and access modifiers aren’t allowed.

// Class
public class MyClass
{
    MyClass()
    {
        // Constructor
    }
    ~MyClass()
    {
        // Destructor
    }
}

6. Can we use access modifiers with destructor?

No, putting an access-modifier on the destructor has no meaning as destructor is called automatically by the Garbage collector (GC) not by the user-written code.

7. What Is Common Language Runtime (CLR) In C#?

The Common Language Runtime (CLR) is an execution engine (Virtual Machine) that provide an environment to manage the execution of programs on target machine written in any of the.NET Framework’s supported programming languages (for example, C#, VB.NET, F#, and so on).

The JIT compiler, which is a component of CLR, converts every source code into a common language known as MSIL or Intermediate Language (IL), which is then executed on the CPU of the computer.
The CLR provides a few of the essential services such as memory management, exception handling, type safety, garbage collection, security, and thread management.

To read more, check out this MSDN article: (CLR) overview

Architecture of Common Language Runtime (CLR) In C#

The following diagram represents the architecture of Common Language Runtime (CLR):

Architecture-of-Common-Language-Runtime-CLR
The architecture of Common Language Runtime (CLR)

8. What is Boxing and Unboxing in C#?

Boxing is the process of converting a value type (int, float, bool, char) to the reference type (object).
it encapsulates the value inside an Object instance and saved it on the managed heap.

Unboxing is the process of converting the reference type(object) into the value type.
Boxing is implicit whereas unboxing is an explicit conversion process.

In the following example, the integer variable number (value type) is boxed and assigned to the object obj (reference type).

//Boxing:
// int 'number' (value type) is created on the Stack
    int number = 100;
// The following line boxes int 'number' and stored it on the Heap (reference type).
    object obj = number;

The object obj is now unboxed and assigned to integer variable myNumber:

// Unboxing:
// The existing boxed int value is unboxed from the managed heap and assigned to int
// myNumber, which is then stored on the stack.

int myNumber = (int)obj;

9. What is the purpose of ‘using’ statement in C#?

Using statement in C# is a simple technique to automatically dispose objects that implement the IDisposable interface in order to free up resources that garbage collection cannot handle automatically.

10. What are partial classes in C# .NET?

C# has a unique feature called a partial class. It has the unique capability of breaking out the functionality of a single class into many files, which are then reassembled into a single class file when the application is compiled.

The partial class allows you to segregate UI design code and business logic code, making it easier to read and understand. (For example, both Default.aspx.cs and Default.designer.cs files in asp.net contain the same class name with the partial keyword, and after compilation, they merge into a single file.)

C# Advanced Interview Questions And Answers

11. What are the differences between string and StringBuilder in C#?

The string is an object of the System.String type. It is immutable (unchangeable), which means that the value once assigned to a String object cannot be changed after its creation.
If we try to update the value of the String object, it will create a new instance with the changed value in a different memory address.

The StringBuilder is a dynamic object that belongs to the System.Text namespace.
It is mutable and doesn’t create a new object in the heap memory every time a new string is concatenated.

To read more, check out this article: C# String VS StringBuilder

12. What is the difference between Finalize() and Dispose() methods in C#?

The main difference between dispose() and finalize() is that the dispose() method belongs to IDisposable Interface and must be called explicitly by the user, whereas the finalize() method is a member of the Object class and is called by the garbage collector right before the object is destroyed.
In C#, you can use the destructor to implement Finalize().

13. What is the difference between ref and out keywords?

Ref keywordOut keyword
1. The ref parameters must be initialized with certain values before passing as method arguments.
Example:
int number = 100;
SomeMethod(ref number);
It is not necessary to initialize out parameters before passing them to a method.
Example:
int number;
SomeMethod(out number);
2. The ref keyword allows data to flow in bi-directions.The out keyword is used to simply get data in one-way mode only.
3. A method cannot return multiple values using the ref.The out keyword comes in handy when a function wants to return many values.
Difference between ref and out keywords in C#

14. What is the difference between is and as operator in C# .NET?

IS Operator: The is operator determines whether or not an object is compatible with a specific type. If the object is of the same type, it returns true; otherwise, it returns false.

AS Operator: The as Operator is used to explicitly convert an Object to a given Type or a Class. The as operator returns null if the conversion isn’t possible.

// Example: Is operator
if(obj is Person)
{
 // Code here ...
}

// Example: As operator
Person p = obj as Person;
if(p != null)
{
   // Code here ...
}

15. What is managed and unmanaged code in c#?

In the.NET Framework, managed code is code that is managed by the CLR (Common Language Runtime). Unmanaged code, on the other hand, is unsafe code that is run directly by the operating system.
The other services such as Garbage collection, type checking, memory allocation, exception handling, and bounds checking, are provided to the managed code by the CLR.

managed and unmanaged code in c#
managed and unmanaged code in c#

16. What are indexers in C# .NET?

Indexer is a smart property in C# that allows an instance of a class or struct to be indexed as a virtual array.
Indexers are defined in the same way as properties but the only difference is that the indexer can be defined using this keyword and square brackets [ ].

       // Example of an Indexer:

       // Declaration of an array
       private string[] array = new string[5];
	   
       // Defining an indexer
       public string this[int i]
       {
          get { return array[i]; }
          set { array[i] = value; }
       }   

To read more about Indexers, check out this article: Indexers in C#

17. Can we define a try block with multiple catch blocks in C#?

Yes, multiple catch blocks can be defined with a single try block in the C# program. The only constraint is that we must specify all derived class exceptions (for example, NullReferenceException, ArgumentNullException, IndexOutOfRangeException, and so on) in the catch block first, and then base class exception (i.e. Exception) should be defined in the last. It means the catch blocks must be placed in the correct order.

try
    {
      // try block
    }
    catch (NullReferenceException ex1)
    {
        // catch Block 1
    }
    catch (ArgumentNullException ex2)
    {
        // catch Block 2
    }
    catch (IndexOutOfRangeException ex3)
    {
        // catch Block 3
    }

    catch (IOException ex4)
    {
        // catch Block 4
    }
    catch (Exception exception)
    {
        // base exception catch block
    }

18. Can multiple catch blocks be executed?

No, multiple catch blocks cannot be executed at the same time. Once the compiler found the suitable catch block to handle the exception, the control never transferred to the next catch block.

19. What is the difference between “throw” and “throw ex” Clause?

The main difference is that the “Throw ex” overwrites the stack trace, making it difficult to locate the original code line number where the exception was thrown.
Throw, on the other hand, essentially keeps the stack information and also provides more precise error information.

Throw vs Throw exception handling
Throw vs Throw exception handling
// Throw:
try 
{
    // code that causes an exception
}
catch (Exception ex)
{  
    throw;
}

// Throw Ex:
try 
{
    // code that causes an exception
}
catch (Exception ex)
{ 
    throw ex;
}

20. What is the difference between finally and finalize block?

    • Finally is a code block executes immediately after the try-catch block, whereas Finalize is a method of Object class.
    • Finally, block in exception handling is used to execute the crucial cleanup-type code to free the resources regardless of whether the try block raised an exception.
    • The finalize method in C# is used to perform clean-up processing just before the object is garbage collected.

21. What is Serialization in C#?

Serialization in C# refers to the process of converting an object into a stream of bytes that can be saved to memory, a file, or a database. Deserialization is the opposite of Serialization, in which an object is created from a stream of bytes.
The SerializableAttribute attribute must be applied to the type in order to serialize the object.
The major goal of serialization is to save an object’s state so that we can restore it whenever we need it, and we can transfer an object to other applications via web or rest services in the form of a stream of bytes.

To read more about Serialization, check out this MSDN article: Serialization (C#)

22. What is the difference between constants and readonly in C#?

    • In C#, Constant variables are declared and initialized at compile-time only. The value once assigned cannot be changed from anywhere in the program including constructors and member functions, whereas the value of a readonly field can be initialized at the time of declaration or in default or parameterized constructor.
    • Readonly fields cannot be declared in methods, but const variables can.
    • A const value is the same for all objects in a program, whereas readonly values can be differ for each objects.
    • The readonly field can be used for run-time constants, while the const field is used for compile-time constants.

23. What is multithreading in C#?

Multithreading allows you to develop applications that perform multiple operations at the same time. Each operation can execute on a separate thread. Multithreading makes an application more responsive and allows you to perform parallel processing so that you can do more than one operation at a time.
You can create a new thread by using the System.Threading.Thread class.

To read more about multithreading, refer to this article: Multithreading (C#)

24. What is Reflection in C#?

In C# .NET, Reflection is the process of retrieving the type from an existing object and accessing its fields, properties, Methods, Events, and other members at the runtime.
The System.Reflection namespace contains types that retrieve information about an assembly. It allows you to create an instance of a type dynamically.
Some of the most commonly used classes in the reflection namespace are Assembly, MethodInfo, PropertyInfo, FieldInfo, EventInfo, ConstructorInfo, etc.

To read more about reflection, refer to this article: Reflection In C#

25. What are Collections in C#?

Collections in C# are a predefined set of specialized classes that are available in the System.Collections namespace for data storage and retrieval. Collections can be used for multiple operations on objects, including storing, updating, retrieving, searching, sorting, and deleting.
Collections are used to work with a group of related objects that can dynamically grow or shrink when objects are added or deleted depending on our needs.
The System.Collections namespace has various commonly used classes such as ArrayList, Hashtable, SortedList, Stack, and Queue.

To read more about Collections, refer to this article: Collections in C#

26. What is Constructor Chaining in C#?

Constructor Chaining is a process of calling one constructor from another constructor in the same class or base class by using this or base keyword.
Following is the example of constructor chaining using this keyword.

using System;
namespace ConstructorChainingExample
{
    class MyClass
    {
       // Constructor
        public MyClass(int setId)
        {
            Id = setId;
        }

        // Calling one constructor from another using 'this' keyword.
        public MyClass(int id, string setName) : this(id)
        {
            //Id = id;
            Name = setName;
        }

        public int Id { get; set; }
        public string Name { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // Here MyClass(10) construct will call by the below mentioned
           // parameterized constructor 
            MyClass obj = new MyClass(10, "Shekh Ali");

            Console.WriteLine($"Id: {obj.Id} Name:{ obj.Name}");
            Console.ReadLine();
        }
    }
    // Output:
    // Id: 10 Name:Shekh Ali
}

27. What is monitor class in C#?

In C#, the Monitor class is a static class that allows you to synchronize access to the critical section of code by locking and releasing a specific object using the  Monitor.Enter ,  Monitor.TryEnter , and  Monitor.Exit  methods. It ensures that only one thread at a time can access a critical section of code. While one thread holds the lock on the object, the other thread cannot acquire the lock.

To read more about monitor class, refer to this article: Monitor class in C#

Monitor Class in Multithreading in C#
Monitor Class in Multithreading in C#

28. What are generics in C#.NET?

Generics is the most powerful feature introduced in C# 2.0 to define type-safe classes, interfaces, methods, events, delegates, and strongly typed generic collections.
A generic type is defined by enclosing a type parameter in angle brackets after the type name, such as TypeName<T>, where T is the type parameter.
Generic types can be used to maximize code reusability, type safety, and performance. All generic collection classes are available in System.Collections.Generic namespace.

To read more about generics, refer to this article: Generics in C# with examples

29. Explain Access Modifiers in C#

Access modifiers are keywords in C# that specify how a class, its properties, fields, and methods are accessible in a program. The access modifiers are mainly used to define the scope of the type and its members, also it is used to safeguard data from being accidentally modified by external classes or programs.
The six access modifiers available in C# are listed below.

    • public
    • protected
    • internal
    • protected internal
    • private
    • private protected

To read more about access modifiers, refer to this article: Access Modifiers in C#

30. Can you declare struct members as protected or protected internal in C#?

Struct members in C# cannot be declared as protected, protected internal, or private protected because structs do not support inheritance.

31. What is the difference between static class and singleton pattern?

Singleton and static classes are both used to provide only one instance of a class that can be accessed globally across the application.
The Following are the main differences:

    • A singleton class can implement interfaces as it supports inheritance, whereas a static class cannot.
    • If it’s a large object, a singleton class can be lazy-loaded, however, a static class is always eagerly loaded.
    • writing unit tests for singleton classes is easier than static classes as you can pass mock objects whenever singleton is expected.
    • A static class can have only static data members whereas a singleton class can have both static and non-static members.
    • Singleton objects can be passed to methods, whereas a static class cannot.

The following is an example of a singleton class.

using System;

public class Singleton
{
   private static Singleton instance;
   // Private Constructor
   private Singleton(){}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}

To read more about the singleton pattern, refer to this MSDN link: Singleton in C#

32. What exactly is the anonymous type in C#?

Anonymous type was introduced in C# 3.0. Anonymous type is a kind of temporary data type that doesn’t have a name and only has public read-only properties.
The compiler automatically generates the type of each property based on the value provided to it. It cannot have other members like class, such as fields, methods, events, etc.
The anonymous type can be created by using the new operator with an object initializer. The var variable is commonly used to store the reference of an anonymous type.

// Example: Access Anonymous Type in C#
     var person = new { Id = 10, Name = "Shekh Ali"};  
     Console.WriteLine($"Id: {person.Id} Name:{ person.Name}");

 // output: Id: 10 Name:Shekh Ali
     Console.ReadLine();

33. Define sealed classes in C#?

In C#, A Sealed class can be created by using the sealed keyword which restricts the class from being inherited.
The sealed keyword indicates to the compiler that the class is sealed and cannot be extended further.
The sealed modifier can be also applied to a method or property in a base class that overrides a virtual method or property. This allows other derived classes to inhrit from your class but prevents them from overriding specific virtual methods or properties that have been declared as sealed.

34. What is multicast delegate in C#?

A multicast delegate is a delegate that holds references to several methods with the same signature in its invocation list. When we call the multicast delegate, all of the methods that the delegate references are called in sequence.
In multicast delegate, We can use Delegate.Combine method or +(plus) operator to chain delegates together and – (minus) operator to remove them from the invocation list.

To read more about multicast delegate, refer to this article: Multicast delegate in C# with examples , MSDN Combine Delegates (Multicast Delegates)

35. What are generic delegates in C#?

The three generic delegates,  Func ,  Action , and  Predicate , were introduced in.NET 3.5 and are available in the System namespace.
When we want to invoke the methods without explicitly defining the delegates, we can use any of these three predefined generic delegates.

Generic delegatesDescription
1. FuncFunc delegate can accept up to 16 input parameters of the same or different data types, as well as a single output parameter.
2. ActionThe Action delegate and the Func delegate are quite similar. It can also take up to 16 input parameters, but it doesn’t return any value.
Action delegate can be used to point those methods that return void and accept zero or more input parameters.
3. PredicateA predicate delegate is generally used to check whether a parameter meets a specific condition or not.
If the requirements are met, it will return true; otherwise, it will return false.
Generic delegates in C#

To read more about Generic delegates, refer to this article: Generic delegates in C#

36. What is the difference between Array and Arraylist in C#?

    • The size of an Array is fixed and cannot be changed dynamically, whereas the size of an ArrayList can be changed dynamically as items are added or removed.
    • Array class is available in System.Array namespace, whereas ArrayList belongs to the System.Collections namespace.
    • An array is a collection that can only contain items of the same data type, but an ArrayList can contain items of different data types.
    • An Array cannot accept null, however null is allowed in the ArrayList.

37. What is an extension method in C#?

Extension methods were introduced in C# 3.0, which allows developers to add new methods to existing classes or structures without having to create new derived types, recompile code, or change the original types.
An extension method is a static method and is always defined in the static class. The first parameter of the extension method must be of the type for which the extension method is suitable, followed by this keyword.

namespace ExtensionMethodsExample
{
    public static class MyExtensionClass
    {   
	   // Extension method applicable for string
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' },
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}

To read more about Extension methods, refer to this article: Extension methods in C#

38. Why this keyword is used in c#?

In C#, the “this” keyword refers to the current instance of the class. It’s also used to distinguish between method arguments and class fields when their names are the same.
This keyword can also be used in constructor chaining to invoke one constructor from another in the same class.

39. Can we use this keyword in static method in C#?

No, we can not used “this” keyword inside a static method. because “this” keyword refers to the current instance of the class, and Static Member functions do not belong to a particular instance. They exist without creating an instance of the class and can be called directly by the class name. However, in an exceptional case, this keyword can be used as the first parameter of the extension methods which is a static method.

40. What is the difference between an interface and abstract class?

    • All the methods of the Interface are abstract by default, with only declaration and no definition. However, an abstract class can contain both abstract and concrete methods.
    • All methods in an interface are public by default, whereas an abstract class can have also private methods.
    • A class can be inherited from multiple interfaces, but a class cannot be inherited from more than one abstract class.
    • An Interface doesn’t contain a constructor, whereas an abstract class can have constructors.

To read more about Interface and abstract class, refer to this article: Top 10 differences between Abstract class and Interface with examples in C#

41. What is the difference between late binding and early binding in C#?

Polymorphism has two concepts: early binding and late binding.
Early binding (also known as static binding) occurs at compile time, when the compiler already knows what type of object it is and what methods or properties it contains.
Late Binding (or dynamic binding) occurs at runtime. In this process, the binding of overridden methods or properties take place at the run time.
The late binding can be achieved by using virtual methods.

42. What is a Jagged Array in C#?

In C#, A jagged array is an array of arrays. Its elements are basically arrays of different sizes.
A jagged array can be initialized using two square brackets [][]. The first square bracket specifies the array’s size, while the second specifies the array’s dimension, which is stored as a value.

Following is an example of jagged array in C#.

namespace JaggedArrayExample
{
    class Program
    {
        static void Main(string[] args)
        {   
            // Declare the array  
            int[][] arr1 = new int[2][];
            // Jagged Array with Two Dimensional Array
           // int[][,] arr2 = new int[4][,];

            arr1[0] = new int[] { 10, 20, 30, 40 };// Initialize the array          
            arr1[1] = new int[] { 55, 65, 75, 85, 95, 100 };

            // Traverse ( or loop) array elements  
            for (int i = 0; i < arr1.Length; i++)
            {
                for (int j = 0; j < arr1[i].Length; j++)
                {
                    System.Console.Write(arr1[i][j] + " ");
                }
                System.Console.WriteLine();
            }
            Console.ReadLine();
        }
    }
    // Output:
    // 10 20 30 40
    // 55 65 75 85 95 100
}

43. What is the difference between Continue and Break Statement?

    • Break: The break statement breaks the loop when a given condition is met.

    • Continue: The continue statement skips one iteration of the loop when a specified condition is met, and resumes with the next iteration.
// Example of break statement:
for (int i = 0; i < 10; i++) 
{
  if (i == 5) 
  {
    break;
  }
  Console.WriteLine(i);
}
// Example of continue statement:
for (int i = 0; i < 10; i++) 
{
  if (i == 5) 
  {
    continue;
  }
  Console.WriteLine(i);
}

44. What is Thread Pooling in C#?

A thread pool is a collection of threads used in a multithreaded application. These threads can be used to perform the new task on-demand instead of creating new threads.
When the task is completed, the thread will return to the thread pool and will be available again.
The System.Threading.ThreadPool namespace contains classes that handle the threads in the pool.

45. What is the difference between an EXE and a DLL?

    • An EXE is a self-executable file that can run by itself, whereas DLL can’t execute independently.
    • A DLL does not have an entry point (main method), whereas an EXE file does.
    • A DLL can be versioned and reused by the other DLL or Executable Files. An EXE, on the other hand, Cannot.
    • A DLL is an in-process component but EXE is an out-process component. When the system launches an EXE, a new process is created, whereas for DLL a new process is not created.
    • A DLL can be reused in the application whereas an EXE Cannot.
    • An EXE stands for executable, whereas DLL stands for Dynamic Link Library

46. What is the difference between string keyword and System.String class?

Basically, there is not much difference between “string” and “String” in C#. “string” keyword is just an alias of the System.String class.
The keyword “string” is widely used to declare a variable, whereas “System.String” is a class and used for accessing string static methods such as String.Format(), String.Compare() , String.Concat etc.

using System;  
namespace ConsoleApplicationDemo {  
    public class Program {  
        public static void Main(string[] args) {
		
            string s1 = "Hello ";  
            string s2 = "World";  
			
            string s3 = String.Concat(s1, s2);  
            Console.WriteLine(s3);  
			Console.ReadLine();  
        }  
    }  
}

47. What is the difference between int.Parse and int.TryParse method in C#?

The  int.Parse()  method throws an exception if the string you are trying to parse is not a valid number, whereas  int.TryParse()  method returns false and doesn’t throw an exception if parsing fails. So int.TryParse() method is more efficient than Parse, It is useful for determining whether or not a string value has been converted to an integer.

48. Give some examples of value types and reference types

    • Value types: Enum, Struct, bool, byte, char, decimal, double, float, int, long
    • Reference types: Class, Interface, Delegate, String, Array

49. What is volatile keyword in C#?

The volatile keyword in C# is to avoid data conflicts when many threads are trying to access the same data at the same time.
The volatile keyword tells the JIT compiler that the value of the field should never be cached since it could be altered by the operating system, hardware, or another thread running at the same time.
As a result, the compiler avoids any optimizations on the variable that might lead to data conflicts because of different threads accessing different values of the variable.

To read more about Interface and Volatile keyword, refer to this article: Volatile (c#)

50. What is enum (enumeration) in C#?

In C#, Enum is a value data type with a set of related named constants, commonly known as an enumerator list. The enum keyword is used to assign names or string values ​​to integer constants, making the program easier to read and maintain. Items in the enum can be declared in curly brackets {} separated by commas. The enum is a user-defined primitive data type that can be integer, float, double, bytes, and so on,but you’ll need to cast it if you use it with int. By default, the underlying type of enumeration elements is integer.

using System;
namespace EnumExample
{
     
    class Program
    { 
    // Declared an enum inside a class  
        enum Season
        {
            Spring = 1,
            Summer = 2,
            Autumn = 3,
            Winter = 4
        }
 
        static void Main(string[] args)
        {
           //Array of string
            string[] seasonNames = Enum.GetNames(typeof(Season));
 
            Console.WriteLine("*** Seasons Names ***");
            //iterate enum variables.
            foreach (var season in seasonNames)
            {             
                Console.WriteLine(season);
            }
                 Console.ReadKey();
        }
    }
}

To read more about enum, refer to this article: C# Enum: How to Use enumeration type in C#?

Thank you for taking the time to read the blog.
A blog without comments isn’t really a blog at all, so If you have any queries or would like to provide feedback, please leave a comment.

Leave a Comment