Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

What is Covariance and Contra variance?

Answer»

Covariance and Contravariance enable implicit reference conversion for array types, delegate types, and generic type arguments. Covariance preserves assignment compatibility and contravariance reverses it.

The following code demonstrates the difference between assignment compatibility, covariance, and contravariance.

// Assignment compatibility.    string STR = "test";   // An object of a more derived type is assigned to an object of a LESS derived type.    object obj = str;   // Covariance.    IEnumerable<string> strings = new List<string>();   // An object that is instantiated with a more derived type argument    // is assigned to an object instantiated with a less derived type argument.    // Assignment compatibility is preserved.    IEnumerable<object> objects = strings;   // Contravariance.              // Assume that the following method is in the class:    // static void SetObject(object o) { }    Action<object> actObject = SetObject;   // An object that is instantiated with a less derived type argument    // is assigned to an object instantiated with a more derived type argument.    // Assignment compatibility is REVERSED.    Action<string> actString = actObject;

Covariance and contravariance support for method GROUPS allows for matching method signatures with delegate types. This enables you to assign to delegates not only methods that have matching signatures, but also methods that return more derived types (covariance) or that accept parameters that have less derived types (contravariance) than that specified by the delegate type.

The following code example shows covariance and contravariance support for method groups.

static object GetObject() { return null; }   static void SetObject(object obj) { }   static string GetString() { return ""; }   static void SetString(string str) { }   static void Test()   {      // Covariance. A delegate specifies a return type as object,      // but you can assign a method that returns a string.      Func<object> DEL = GetString;      // Contravariance. A delegate specifies a parameter type as string,      // but you can assign a method that takes an object.      Action<string> del2 = SetObject;   }

In .NET Framework 4 or newer C# supports covariance and contravariance in generic interfaces and delegates and allows for implicit conversion of generic type parameters

The following code example shows implicit reference conversion for generic interfaces.

IEnumerable<String> strings = new List<String>();   IEnumerable<Object> objects = strings;
2.

What is difference between Stack and Heap memory in C#?

Answer»

Stack

  • Stack is an array of memory.
  • It is a Last-in, First-out (LIFO) data structure.
  • Data can be added to and deleted only from the top of the stack.
  • Placing a data item at the top of the stack is called pushing the item onto the stack.
  • Deleting an item from the top of the stack is called popping the item from the stack.

Heap

The heap is an area of memory where chunks are allocated to store certain kinds of data objects. UNLIKE the stack, data can be STORED and removed from the heap in any order. CLR’s garbage collector (GC) automatically cleans up orphaned heap objects when it determines that your CODE can no longer access them.

Difference between Stack and Heap Memory

Stack MemoryHeap Memory
Static memory allocationDynamic memory allocation
Variables allocated on stack are directly stored to memoryVariables allocated on Heap have their memory allocated at runtime
Variables cannot be re-sizedVariables can be re-sized
Very fast accessRelatively slow access
Variables stored on stack are visible only to the owner threadObjects created on the heap are visible to all threads.
Stack is ALWAYS reserved in LIFO order, the most recently reserved block is always the next block to be freed.You can allocate a block and free it at any time.
The  moment stack space is exhausted, .NET runtime throws StackOverflowException.Memory.NET runtime creates special thread that monitors allocation of heap space called Garbage Collector
3.

What is Generics?

Answer»

Generics are the most powerful features introduced in C# 2.0. It is a type-safe data structure that allows us to write codes that works for any data types.

For example, by using a generic type parameter T you can write a single class that other CLIENT code can use without incurring the COST or risk of runtime casts or boxing operations

// DECLARE the generic class. public class GenericList<T&GT; {    public void Add(T INPUT) { } } class TestGenericList {    private class ExampleClass { }    static void Main()    {        // Declare a list of type int.        GenericList<int> list1 = new GenericList<int>();        list1.Add(1);        // Declare a list of type string.        GenericList<string> list2 = new GenericList<string>();        list2.Add("");        // Declare a list of type ExampleClass.        GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();        list3.Add(new ExampleClass());    } }
4.

What is dynamic keyword?

Answer»

DYNAMIC is a new static type that acts like a placeholder for a type not known until runtime. Once the dynamic object is declared, it is possible to call operations, get and set properties on it, even pass the dynamic instance pretty much as if it were any normal type.

The dynamic type enables the operations in which it occurs to BYPASS compile-time type checking. these operations are resolved at run time. Type dynamic behaves like type object in most circumstances. However, operations that contain expressions of type dynamic are not resolved or type checked by the compiler.

As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time.

The following example contrasts a variable of type dynamic to a variable of type object. To verify the type of each variable at compile time, place the mouse pointer over dyn or obj in the WRITELINE statements. IntelliSense shows dynamic for dyn and object for obj.

class Program {    static void MAIN(string[] args)    {        dynamic dyn = 1;        object obj = 1;        // Rest the mouse pointer over dyn and obj to see their        // types at compile time.        System.Console.WriteLine(dyn.GetType());        System.Console.WriteLine(obj.GetType());    } }

Limitations of dynamic

  •  Extension methods cannot be called
  •  Anonymous functions (lambdas) cannot be called
  •  Because of the above, LINQ support is limited
5.

What is the difference between Composition and Aggregation?

Answer»

Composition

Like Inheritance gives us an 'is-a' relationship. Composition gives us a 'part-of' relationship. Composition is shown on a UML diagram.

If we were going to model a car, it would make sense to say that an engine is part-of a car. Within composition, the LIFETIME of the part (Engine) is managed by the WHOLE (Car), in other WORDS, when Car is destroyed, Engine is destroyed ALONG with it.

public class Engine {  . . . } public class Car {    Engine e = new Engine();    ....... }

As you can see in the example code above, Car manages the lifetime of Engine.

Aggregation

As Inheritance gives us 'is-a' and Composition gives us 'part-of', Aggregation gives us a 'has-a' relationship. Within aggregation, the lifetime of the part is not managed by the whole.

For Example:

Aggregation would make sense in this situation, as a Person 'has-a' Address. It wouldn't make sense to say that an Address is 'part-of' the Person, because it isn't. Consider it this way, if the person ceases to exist, does the address

So how do we express the CONCEPT of aggregation in C#? Well, it's a little different to composition. Consider the following code:

public class Address {  . . . } public class Person {     private Address address;     public Person(Address address)     {         this.address = address;     }     . . . }

Person would then be used as follows:

Address address = new Address(); Person person = new Person(address);

or

Person person = new Person( new Address() );

Here  Person does not manage the lifetime of Address. If Person is destroyed, the Address still exists.


6.

What is early and late binding?

Answer»

Early Binding

The NAME itself describes that compiler knows about what kind of object it is, what are all the methods and properties it contains. As soon as you declared the object, .NET Intellisense will populate its methods and properties on click of the DOT button

Common Examples:

  • ComboBox cboItems;
  • ListBox lstItems;

In the above examples, if we type the cboItem and place a dot followed by, it will automatically populate all the methods, events and properties of a combo box, because compiler already know it's an combobox.

Late Binding
The name itself describes that compiler does not know what kind of object it is, what are all the methods and properties it contains. You have to DECLARE it as an object, LATER you need get the type of the object, methods that are stored in it. Everything will be known at the run time.

Common Examples:

  • Object objItems;
  • objItems = CreateObject("DLL or Assembly name");

Here during the compile time, type of objItems is not determined. We are creating an object of a dll and assigning it to the objItems, so everything is determined at the run time.

7.

What is serialization?

Answer»

When we WANT to transport an object through network then we need to convert the object into a stream of BYTES. Serialization is a process to convert a COMPLEX objects into stream of bytes for storage (database, file, cache, etc) or transfer. Its main purpose is to save the state of an object.
De-serialization is the reverse process of creating an object from a stream of bytes to their original form.

Types of Serialization:

Serialization is of following types:

  • Binary Serialization
    In this process all the PUBLIC, private, read only MEMBERS are serialized and convert into stream of bytes. This is used when we want a complete conversion of our objects.
  • SOAP Serialization
    In this process only public members are converted into SOAP format. This is used in web services.
  • XML Serialization
    In this process only public members are converted into XML. This is a custom serialization. Required namespaces: System.Xml, System.Xml.Serialization.

Serialization is used in the following purposes:

  • To pass an object from on application to another
  • In SOAP based web services
  • To transfer data through cross platforms, cross devices
8.

What is Abstraction and Encapsulation?

Answer»
  • Abstraction

Abstraction means to show only the necessary details to the client of the object. Abstraction is the process of refining AWAY all the unneeded/unimportant attributes of an object and keep only the characteristics best suitable for your DOMAIN. Abstraction means putting all the variables and methods in a class which are necessary.

Encapsulation is a strategy used as part of abstraction. Encapsulation refers to the state of objects - objects encapsulate their state and hide it from the outside; outside users of the class interact with it through its methods, but cannot access the CLASSES state directly. So the class abstracts away the implementation details related to its state. It is a method for PROTECTING data from unwanted access or alteration. Encapsulation is the mechanism by which Abstraction is implemented.

Difference between Abstraction and Encapsulation

AbstractionEncapsulation
solves the problem in the design level.solves the problem in the implementation level.
hiding the unwanted data and giving only relevant data.hiding the code and data into a single unit to protect the data from outer world
set focus on the object instead of how it does ithiding the internal details or mechanics of how an object does something
9.

What is UnSafe Code?

Answer»

In ORDER to maintain security and type safety, C# does not support pointer generally. But by using unsafe keyword we can define an unsafe context in which pointer can be used. The unsafe code or unmanaged code is a code block that uses a pointer variable. In the CLR, unsafe code is referred to as unverifiable code. In C#, the unsafe code is not necessarily dangerous. The CLR does not verify its safety. The CLR will only execute the unsafe code if it is within a fully trusted assembly. If we use unsafe code, it is our own responsibility to ensure that the code does not introduce security RISKS or pointer errors.

Unsafe code cannot be executed in an un-trusted environment. For example, we cannot run unsafe code directly from the Internet

Some properties of unsafe codes are given bellow:

  • We can define Methods, types, and code blocks as unsafe
  • In some cases, unsafe code may increase the application’s performance by removing array bounds checks
  • Unsafe code is required in order to call native functions that require pointers
  • Using unsafe code BRINGS security and stability risks
  • In order to compile unsafe code, the application must be COMPILED with /unsafe
10.

What is the use of using keyword?

Answer»

There are two ways to USE the using keyword in C#. One is as a directive and the other is as a statement.

1. Using Directive

Generally we use the using keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties in the current page. Adding a namespace can be done in the following two ways:

  • To allow the NORMAL use of types in a namespace:
    • using System.IO;  
    • using System.Text;  
  • To create an alias for a namespace or a type. This is called a using alias directive. 
    • using MyProject = TruckingApp.Services; 

2. Using Statement

This is another way to use the using keyword in C#. It plays a vital role in improving performance in Garbage Collection.

The using statement ensures that Dispose() is called even if an exception occurs when you are creating objects and calling methods, properties and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom Garbage Collection. In other words if I am doing some database operation (Insert, Update, Delete) but somehow an exception occurs then here the using statement closes the connection automatically. No NEED to call the connection Close() method explicitly.

Another important factor is that it helps in Connection Pooling. Connection Pooling in .NET helps to ELIMINATE the closing of a database connection multiple times. It sends the connection object to a pool for future use (next database call). The next TIME a database connection is called from your application the connection pool fetches the objects available in the pool. So it helps to improve the performance of the application. So when we use the using statement the controller sends the object to the connection pool automatically, there is no need to call the Close() and Dispose() methods explicitly

For Example:

   string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";      using (SqlConnection conn = new SqlConnection(connString))      {          SqlCommand cmd = conn.CreateCommand();            cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";            conn.Open();            using (SqlDataReader dr = cmd.ExecuteReader())            {             while (dr.Read())               Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));            }    }
11.

What is Private Constructor, what is the use of it?

Answer»

A private constructor is a special instance constructor. It is generally used in CLASSES that contain static members only. If a class has one or more private constructors and no public constructors, other classes (EXCEPT nested classes) cannot create INSTANCES of this class. For example:

class NLOG {    // Private Constructor:    private NLog() { }    public static double e = Math.E;  //2.71828... }

The declaration of the empty constructor prevents the AUTOMATIC generation of a default constructor.

Note that if you do not use an access modifier with the constructor it will still be private by default.

Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.

12.

What are async-await?

Answer»

Async-await is used to perform action asynchronously. It is required when there are long running activities, processing them synchronously may take long time and become blocker to web access. In an asynchronous process, the application can continue with other work that doesn't depend on the web resource until the potentially blocking task finishes.

The async and await keywords in C# are the heart of async programming. By using those two keywords, you can use resources in the .NET Framework. Asynchronous methods that you define by using the async keyword are referred to as async methods.

The following EXAMPLE SHOWS an async method.

// Three things to note in the signature:   //  - The method has an async modifier.    //  - The return type is Task or Task<T>. (See "Return TYPES" section.)   //    Here, it is Task<int> because the return statement returns an integer.   //  - The method name ends in "Async."   async Task<int> AccessTheWebAsync()   {       // You need to add a reference to System.Net.Http to declare client.      HttpClient client = new HttpClient();      // GetStringAsync returns a Task<string>. That means that when you await the      // task you'll get a string (urlContents).      Task<string> getStringTask = client.GetStringAsync("https://msdn.microsoft.com");      // You can do work here that doesn't rely on the string from GetStringAsync.      DoIndependentWork();      // The await operator suspends AccessTheWebAsync.      // - AccessTheWebAsync can't continue until getStringTask is complete.      // - Meanwhile, control returns to the caller of AccessTheWebAsync.      // - Control resumes here when getStringTask is complete.       // - The await operator then retrieves the string result from getStringTask.      string urlContents = await getStringTask;      // The return statement specifies an integer result.      // Any methods that are awaiting AccessTheWebAsync retrieve the length value.      return urlContents.Length;   }

For a method to be async, it should have following characteristics:

  • The method signature includes an async modifier.
  • The return type is one of the following types:
    • if method have a return statement then Task<TResult>.
    • if no return statement  then Task.
  • The method usually includes at least one await expression.

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization CONTEXT and uses time on the thread only when the method is active.

An async method typically returns a Task or a Task<TResult>. Inside an async method, an await operator is applied to a task that's returned from a call to another async method. You specify Task<TResult> as the return type if the method contains a return statement that specifies an operand of type TResult.

You use Task as the return type if the method has no return statement or has a return statement that doesn't return an operand. An async method can't declare in, ref or out parameters, but the method can call methods that have such parameters. Similarly, an async method can't return a value by reference, although it can call methods with ref return VALUES

13.

What is Func, Action and Predicate?

Answer»

Func, Action and PREDICATE are define in C# 3.0 and these are generic inbuilt delegates.

  • Func Delegate

Func is generic delegate present in System namespace. It takes one or more input parameters and returns one out parameter. The last parameter is considered as a return value.

Func delegate TYPE can include 0 to 16 input parameters of different types. It must have one return type. So return type is mandatory but input parameter is not.

Example1: Func delegate with two input parameters and one return value.

   Func func1 = DelegateClass.Add;      int value = func1(10, 20);      TParameter = 10,20;      TOutput = value = 30;  

Example 2: Func delegate with one input parameter and one return value.

   Func func2 = DelegateClass.GetValue;      int values = func2(30);      TParameter = 30      TOutput = 40;  

Example 3: Func delegate with zero input parameter and one return value.

   Func func3 = DelegateClass.GetResult;      intresultMulti = func3();      TParameter = Nothing      TOutput = 600;      Func with Anonymous methods:      Func func4= delegate(intx,int y){ return (x+y); };      int result = func4(2,3);      Func with Lambda EXPRESSION:      Func func5= (intx,int y) => { return (x+y); };      int xx = func4(2,3);  
  • Action Delegate

Action is a generic delegate present in System namespace. It takes one or more input parameters and returns nothing.

So it does not return any value.

Example 1: Action delegate with two input parameters.

   Action action1=DelegateClass.ShowEmploye;      action1(30,"Rajesh");      TParameter = 30,Rajesh;      TOutput = Not available (No return value)  

Example 2: Action delegate with one input parameter.

   Action action2=DelegateClass.ShowMessage;      action2("Rajesh");      TParameter = “Rajesh”      TOutput = Not available   Action delegate with Anonymous methods:    Action action = delegate(String msg)      {        Console.WriteLine(msg);      };    action("rajesh");      Action delegate with Lambda expression: Action action = (msg) = & gt;      {        Console.WriteLine(msg)      };    action(“Rajesh”);  
  • Predicate Delegate

Predicate delegate is also inbuilt generic delegate and is present in System namespace.

It is used to verify certain CRITERIA of method and returns output as Boolean, either True or False.

Predicate can be used with method, anonymous and lambda expression.

Example 1: Check String value is number using Predicate delegates.

Predicate predicate = DelegateClass.IsNumeric; bool number = predicate("1234");

Example 2: Predicate delegate using Anonymous method.

   Predicate predicate = delegate(string str)      {        double retNum;          bool isNum = Double.TryParse(Convert.ToString(str), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);          return isNum;      };    bool found = predicate("12232");  

Example 3: Predicate delegate using lambda expression.

   Predicate predicate = (str) = & gt;      {        double retNum;          bool isNum = Double.TryParse(Convert.ToString(str), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);          return isNum;      };    bool found = predicate("12232");
14.

What is Garbage Collector?

Answer»

GARBAGE collector manages allocation and reclaiming of memory. GC (Garbage collector) makes a trip to the heap and collects all objects that are no longer used by the application and then makes them free from memory.

Each time you create a new object, the common language runtime allocates memory for the object from the managed heap. As long as address space is available in the managed heap, the runtime continues to allocate space for new objects. However, memory is not infinite. Eventually the garbage collector must perform a collection in order to free some memory. The garbage collector's optimizing engine determines the best time to perform a collection, based upon the allocations being made. When the garbage collector performs a collection, it checks for objects in the managed heap that are no longer being used by the application and performs the necessary operations to reclaim their memory.

Garbage collection occurs when one of the following conditions is true:

  • The system has low physical memory. This is detected by either the low memory notification from the OS or low memory indicated by the host.
  • The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.
  • The GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.

Managed Heap

After the garbage collector is initialized by the CLR, it allocates a segment of memory to store and manage objects. This memory is called the managed heap, as opposed to a native heap in the operating system.

When the garbage collector is triggered, it reclaims the memory occupied by dead objects, also compacts the live objects so that they are moved together and dead space is removed. This way it makes the heap smaller and ensure that allocated objects stay together on managed heap. 

Based on object life heaps can be considered as accumulation of two heap: large object heap and small object heap.Heap is managed by DIFFERENT 'Generations', it stores and handles long-lived and short-lived objects, SEE the below generations of Heap:

  • 0 Generation (Zero): This generation holds short-lived objects, e.g., Temporary objects. GC initiates garbage collection process frequently in this generation.
  • 1 Generation (One): This generation is the buffer between short-lived and long-lived objects.
  • 2 Generation (Two): This generation holds long-lived objects like a static and global variable, that needs to be persisted for a CERTAIN amount of time. Objects which are not collected in generation Zero, are then moved to generation 1, such objects are known as survivors, similarly objects which are not collected in generation One, are then moved to generation 2 and from there onwards objects remain in the same generation.

What happens during a garbage collection

Following phases are there of garbage collection:

  • Marking Phase: that finds and creates a list of all live objects.
  • Relocating Phase: that updates the references to the objects that will be compacted.
  • Compacting Phase: that reclaims the space occupied by the dead objects and compacts the surviving objects. It moves objects that have survived a garbage collection toward the older END of the segment.
15.

What is the difference between Interface and Abstract class?

Answer»
  • Abstract Class

An abstract class is a special kind of class that can be inherited but cannot be instantiated. For a class to be an abstract class, there should always be at least one abstract METHOD should be present.

  • Interface

Interface is not a class, it is an entity that is defined by the work Interface. Like Abstract class we cannot create an instance of Interface. It has no implementation; only has the signature i.e. just the definition of the methods without the body.

Advantage of Interface is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

Difference between Interface and Abstract Class

Feature
InterfaceAbstract class
Multiple inheritance
A class can inherit to multiple interfacesA class may inherit from only one abstract class.
Default implementationAn interface only have method declaration, no definition.An abstract class can have methods with complete definition or abstract methods that to be overriden in derived class
Access Modifiersfor interface everything is assumed as publicAn abstract class have access modifiers for the subs, functions, properties
HomogeneityInterfaces are better OPTION when various IMPLEMENTATIONS share the same method signature.Abstract classes are better when various implementations are of the same kind and use common behaviour or status.
Adding functionality (Versioning)Adding a new method to interface need to implemented in derived classeswhile adding new method we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and CONSTANTSNo fields can be definedcan have fields and constants defined
16.

What is the C# Equivalent to C++ Function Pointers?

Answer»

Delegates is the C# EQUIVALENT to function pointers. However, unlike function pointers, the delegates ENCAPSULATE both an OBJECT instance and a method.

Delegates are fully object oriented and allow methods to be passed as PARAMETERS.

17.

System.Array.CopyTo() vs System.Array.Clone() in C#

Answer»

Details about System.Array.CopyTo() and System.Array.Clone() are given as follows:

System.Array.CopyTo()

This method copies all the ELEMENTS that are in the current one-dimensional array into the one-dimensional array that is specified. The two parameters of the method are the array that is the destination array of the elements copied from the current array and the the index at which the array copying starts.

A program that DEMONSTRATES this is given as follows:

using System.IO; using System; class Demo {   public static void Main()   {      int[] source = new int[5] {6, 8, 1, 4, 7};      int[] target = new int[5];      source.CopyTo(target, 0);      Console.WriteLine("The target array is: ");      foreach (int i in target)      {          Console.WriteLine(i);      }   } }

The output of the above program is given as follows:

The target array is: 6 8 1 4 7

System.Array.Clone()

This method creates a shallow copy of the array and returns it. Also, the  System.Array.Clone() method is slower than the System.Array.CopyTo() method.

A program that demonstrates this is given as follows:

using System.IO; using System; class Demo {   public static void Main()   {      int[] source = new int[5] {6, 8, 1, 4, 7};      int[] target = new int[5];      target = (int[])source.Clone();      Console.WriteLine("The target array is: ");      foreach (int i in target)      {          Console.WriteLine(i);      }   } }

The output of the above program is given as follows:

The target array is: 6 8 1 4 7
18.

Can we create an array with non-default values in C#?

Answer»

YES, we can create an ARRAY with non-default values. This can be ACHIEVED USING Enumerable.Repeat in C#.

19.

Why Environment.Exit() used in C#?

Answer»

The Environment.EXIT() method is USED in C# to TERMINATE this process. An exit CODE is returned by the method. For example, Environment.Exit(2) returns a value 2 showing that the file is in an incorrect format.

20.

Why do we write “using” in a C# Program?

Answer»

The using keyword in C# is used to specify the NAMES of the namespaces that are used in the given program. For example - The System namespace is used in the programs with the keyword using.

A program that demonstrates the using keyword in C# is given as FOLLOWS:

using System; namespace Demo {    class Test    {      STATIC VOID Main(string[] args)      {         int a, b, sum;         a = 14;         b = 2;         sum = a + b;         Console.WriteLine("The sum of {0} and {1} is {2}", a, b, sum);      }    } }

The output of the above program is as follows:

The sum of 14 and 2 is 16
21.

What is the C# equivalent of C++ friend keyword?

Answer»

The equivalent of C++ friend KEYWORD in C# is a nested class accessing the OUTER class PRIVATE members. That would MEAN the INNER class can access the outer class private members:

22.

How to work with Generics in C#?

Answer»

Classes and methods in C# can be created using Generics that defer the specification of TYPES until the class or METHOD is declared. This means that the creation of classes and methods that work with any data type can be handled using Generics.

A Generic class can be defined using angle brackets <>. There are type parameters that are Generic. These can handle any data type that is specified in a Generics class. Also, a Generic method is a method that is declared by using type parameters.

A program that demonstrates generic class and generic method in C# is given as FOLLOWS:

using System; public class GenericClass<T> {    private T GenericMember;    public GenericClass(T data)    {        GenericMember = data;    }    public T GenericMethod(T GenericParameter)    {        Console.WriteLine("The Generic parameter is: {0}",  GenericParameter);        return GenericMember;    }    public T genericProperty { get; set; } } public class Program { public static void Main() { GenericClass<CHAR> GenericObject1 = new GenericClass<char>('D'); GenericClass<int> GenericObject2 = new GenericClass<int>(70);        char num1;        int num2;        Console.WriteLine("For a character variable");        num1 = GenericObject1.GenericMethod('A');        Console.WriteLine("The Generic member variable is: {0}",  num1);        Console.WriteLine("For an integer variable");        num2 = GenericObject2.GenericMethod(50);        Console.WriteLine("The Generic member variable is: {0}",  num2); } }

The output of the above program is as follows:

For a character variable The Generic parameter is: A The Generic member variable is: D For an integer variable The Generic parameter is: 50 The Generic member variable is: 70
23.

Why is a Dictionary preferred over a Hashtable in C#?

Answer»

Dictionary and Hashtable are Collections classes in C#. Hashtable class is a COLLECTION of key-and-value PAIRS organized based on the hash CODE of the key.

Dictionary is a collection of keys and values. Hashtable is SLOWER than Dictionary. For strongly-typed collections, the Dictionary collection is faster and you prefer them.

24.

Why do we use the AssemblyQualifiedName Property in C#?

Answer»

The AssemblyQualifiedName property DISPLAYS the QUALIFIED assembly name associated with a TYPE. The program that demonstrates this property is as follows:

using System;   using System.Reflection;   public class Demo   {      public static VOID Main()      {         Type t = TYPEOF(System.Object);        Console.WriteLine ("Qualified assembly name:\n   {0}.", t.AssemblyQualifiedName.ToString());    } }

The output of the above program is as follows:

Qualified assembly name:
System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.

25.

What is Unsafe Code in C#?

Answer»

Unsafe code in general is a keyword that denotes a code section that is not handled by the Common Language Runtime (CLR). Pointers are not supported by default in C# but unsafe keyword allows the use of the pointer variables.

However, extra care is required while handling unsafe code to PREVENT errors or security risks as pointers are complex and may LEAD to memory related errors such as stack overflow, overwritten system memory etc.

The following is an example:

using System; namespace PointerDemo {   class Example   {      STATIC unsafe void Main(STRING[] args)      {         char val = 'A';         char* PTR = &val;         Console.WriteLine("The character value is: {0} ", val);         Console.WriteLine("Address of the value is: {0}", (int)ptr);      }   } }

The output of the above program is as follows:

The character value is: A Address of the value is: 220412608
26.

Why to perform Interning of Strings in C#?

Answer»

To PERFORM Interning of strings, use the Intern() method. Use interning to OPTIMIZE application’s MEMORY. The common language RUNTIME conserves string storage by maintaining a table, called the intern pool.

The intern() method retrieves the reference to the particular string. The SEARCH for a string equal to the particular String is done in Intern Pool.

27.

What is the difference between method overloading and method overriding in C#?

Answer»

In METHOD OVERRIDING, the PARAMETERS are the same. In method OVERLOADING, the parameters are DIFFERENT.

28.

Best Practices in C#

Answer»

C# is a general purpose object-oriented programming language with multiple paradigms. It was designed for Common Language Infrastructure (CLI) in 2000 by Microsoft.

C# has multiple advantages to CONTRIBUTE to the speed of web development solutions. Some of these are  SCALABILITY support, garbage collection, type safety, easier type declarations etc.

Best Practices to write better C# code

Some of the best practices that help in WRITING better C# code are given as follows:

  1. PASCAL casing should be used for method names and class names while Camel Casing should be used for local variables and method arguments.
  2. Underscore should not be used in identifiers.
  3. All member variables should be declared at the class top and at the topmost should be static variables.
  4. The class sizes should be small for greater efficiency.
  5. There should be no obsolete comments in the code. They should be updated if required.
  6. The methods should be short.
  7. There should be no unnecessary regions in the class.
  8. The complex expressions should be avoided.
  9. In a particular routine, there should be minimum NUMBER of returns.
29.

Define the rank of an array in C#

Answer»

The rank of an array is the number of dimensions of an array. For EXAMPLE - The rank of a one-dimensional array is 1, the rank of a TWO dimensional array is 2 and so on. The rank of a jagged array is 1 as it is a one-dimensional array. The rank of any array can be found using the Array.Rank property.

A program that demonstrates the rank of an array in C# is given as follows:

using System; namespace Demo {    class Program    {        static void Main(string[] ARGS)        {            int[] arr1 = new int[10];            int[,] ARR2 = new int[4, 5];            int[][] arr3 = new int[5][];            Console.WriteLine("Rank of Array 1 is: " + arr1.Rank);            Console.WriteLine("Rank of Array 2 is: " + arr2.Rank);            Console.WriteLine("Rank of Array 3 is: " + arr3.Rank);        }    } }

The output of the above program is as follows:

Rank of Array 1 is: 1 Rank of Array 2 is: 2 Rank of Array 3 is: 1
30.

What is the role of final variables in C#?

Answer»

There are no final variables in C# as the keyword final is available in Java and not in C#. The KEYWORDS readonly and sealed in C# have the same IMPLEMENTATION as final in Java.

Details about readonly and sealed in C# are given as follows:

  • The readonly keyword

In a field declaration, the readonly keyword specifies that assignment for a field can only occur with declaration or using the constructor of the same class. A program that demonstrates the readonly keyword is given as follows:

using System; class Student {    readonly INT rollNo;    public Student(int rno)    {        rollNo = rno;    }    public int getRollNumber()    {        // rollNo = 7;        return this.rollNo;    } } public class Demo {    public static void Main()    {        Student s = new Student(105);        Console.WriteLine("Roll Number: " + s.getRollNumber());    } }

The output of the above program is as follows:

Roll Number: 105

In the above program, the variable rollNo is readonly and so it cannot be assigned a value in method getRollNumber(). So if the comments are removed, an error would be obtained.

  • The sealed keyword

The sealed keyword is used in classes to restrict inheritance. So sealed classes are those classes that cannot be extended and no class can be derived from them.

A program that demonstrates the sealed keyword in C# is given as follows:

using System; sealed class A {       int a = 5;    public int returna()    {        return a;    } } class Demo {    static void Main(string[] args)    {        A OBJ = new A();        Console.WriteLine("a = " + obj.returna());    } }

The output of the above program is as follows:

a = 5

In the above program, the class A is a sealed class. This means that it cannot be inherited and an error will be generated if any class is derived from the class A.

31.

Typeof() vs GetType() in C#

Answer»

The major difference between Typeof() and GETTYPE() is that while Typeof() obtains the type based on the class, GetType() obtains the type based on the OBJECT. DETAILS about both of them in C# are given as follows:

  • Typeof()

The Typeof() method is used to get the System.Type object for a given type. Also, this method can be used on open generic types but it cannot be overloaded.

A program that DEMONSTRATES the Typeof() method in C# is given as follows:

using System; using System.IO; class Demo {    public static void Main()    {        Console.WriteLine(typeof(int));        Console.WriteLine(typeof(char));        Console.WriteLine(typeof(double));        Console.WriteLine(typeof(int[]));        Console.WriteLine(typeof(Array));        Console.WriteLine(typeof(Stream));        Console.WriteLine(typeof(TextWriter));    } }

The output of the above program is as follows:

System.Int32 System.Char System.Double System.Int32[] System.Array System.IO.Stream System.IO.TextWriter
  • GetType()

The GetType() method obtains the type of the current object of the class. A program that demonstrates the GetType() method in C# is given as follows:

using System; class Animal { } class Mammal : Animal { } class Human : Mammal { } class Demo {    static void Main()    {        Animal obj1 = new Animal();        Animal obj2 = new Mammal();        Animal obj3 = new Human();        Console.WriteLine(obj1.GetType());        Console.WriteLine(obj2.GetType());        Console.WriteLine(obj3.GetType());    } }

The output of the above program is as follows:

Animal Mammal Human
32.

What is a Multicast Delegate in C#?

Answer»

If a Delegate invokes MULTIPLE METHODS, these are called Multicast Delegates.

Let us see an example:

using System;   using System.Collections.Generic;   using System.Linq;   using System.Text;   delegate VOID DemoDelegate();   CLASS Example   {      static public void One()      {        Console.WriteLine("One");      }    static public void Two()      {        Console.WriteLine("Two");      }    static public void Three()      {        Console.WriteLine("Three");      } }   class DEMO   {      public static void Main()      {        DemoDelegate d1 = new DemoDelegate(Example.One);          DemoDelegate d2 = new DemoDelegate(Example.Two);          DemoDelegate d3 = new DemoDelegate(Example.Three);          DemoDelegate d4 = d1 + d2 + d3;          DemoDelegate d5 = d2 + d3 + d4;          DemoDelegate d6 = d3 - d4 + d5;        d3();        d4();        d5();        d6();    } }

The output:

Three One Two Three Two Three One Two Three Two Three One Two Three
33.

Does Mixed Arrays still exist in C#?

Answer»

The concept of Mixed arrays is OBSOLETE since .NET 4.0. Since it does not exist now, you can use LIST collection in C#.

An example is:

Tuple<INT, string> t = new Tuple<int, string>(200, "This is fine!");
34.

What are Anonymous Methods in C#?

Answer»

A method without a name is Anonymous Method. It is defined USING the delegate keyword.

The Anonymous methods can be assigned to a variable of delegate type. It can also be passed as a parameter. Here are some of the features of Anonymous Methods in C#:

  • Anonymous methods are defined using the delegate keyword.
  • Anonymous methods can be used in event handling.
  • Any unsafe CODES cannot be accessed inside anonymous methods.
  • Variables declared outside the anonymous methods can be accessed inside them.
  • Variables declared inside the anonymous methods cannot be accessed outside them.
  • Anonymous methods can be passed as parameters.

The following is an example:

using System; public delegate void DemoDelegate(int value); public CLASS Example {   public STATIC void Display(DemoDelegate one,int a)    {        a *= 50;        one(a);    }    public static void Main(string[] args)    {        Display(delegate(int a) { Console.WriteLine("Anonymous method = {0}", a); }, 100);    } }

The output: 

Anonymous method = 5000

Let US see another example: 

using System; namespace AnonymousMethodDemo {   class Example {      public delegate void sum(int x, int y);      static void Main(string[] args)      {         sum s = delegate(int x, int y)         {           Console.WriteLine("Inside Anonymous method");           Console.WriteLine("Sum = {0}",x + y);         };         s(7, 12);      }   } }

The output of the above program is as follows:

Inside Anonymous method Sum = 19
35.

Why nullable data types introduced in C#?

Answer»

Assign a null VALUE to variable with NULLABLE DATA types. It was INTRODUCED in C# 2.0 for the same purpose as well as assign values other than null. An example: 

int? a = null;

Above, we have assigned a null value to a variable.

36.

What is a default constructor? Does it take zero arguments. Is it correct?

Answer»

A default CONSTRUCTOR takes no arguments. Each object of the class is initialized with the default values that are specified in the default constructor. Therefore, it is not possible to initialize the DIFFERENT objects with different values.

An example that demonstrates a default constructor is given as follows:

USING System; namespace DefaultConstructorDemo {   class Sum   {     private int x;     private int y;     public Sum()     {         x = 5;         y = 7;     }     public int getSum()     {         return x + y;     }      }    class Test    {      STATIC void Main(STRING[] args)      {         Sum s = new Sum();            Console.WriteLine("Sum: {0}" , s.getSum());      }    } }

The output of the above program is as follows:

Sum: 12

Now let us understand the above program.

First, the class Sum is initialized. It contains two private variables x and y. The default constructor Sum() initializes x and y to 5 and 7 respectively. Then the function getSum() returns the sum of x and y. The code snippet for this is given below:

class Sum   {     private int x;     private int y;     public Sum()     {         x = 5;         y = 7;     }     public int getSum()     {         return x + y;     }    }

The main() function is in the class Test. It initializes an object s of class Sum. Then the sum of 5 and 7 is displayed using getSum(). The code snippet for this is given below:

class Test    {      static void Main(string[] args)      {         Sum s = new Sum();            Console.WriteLine("Sum: {0}" , s.getSum());      }    }
37.

Why do we use Array.SyncRoot property of array class in C#?

Answer»

The ARRAY.SyncRoot property gets an OBJECT used to synchronize access to the Array. USE the SyncRoot property to implement their own SYNCHRONIZATION. This USAGE is for classes having arrays.

38.

What is the first thread that is created and executed inside a process in C#?

Answer»

The Main Thread is the first thread that is created and executed inside a process. It is AUTOMATICALLY created when the process starts execution.

A program that demonstrates the Main thread is given as follows:

using System; using System.Threading; namespace MultithreadingDemo {   class Example   {      static void Main(string[] args)      {         Thread myThread = Thread.CurrentThread;         myThread.NAME = "Main_Thread";         Console.WriteLine("This thread is the {0}", myThread.Name);      }   } }

The output of the above program is as follows:

This thread is the Main_Thread

Now let US understand the above program.

The CurrentThread PROPERTY of the Thread class is used to access the Main thread. The name of the thread is specified is Main_Thread. After that, this is displayed. The code snippet for this is given as follows:

Thread myThread = Thread.CurrentThread; myThread.Name = "Main_Thread";          Console.WriteLine("This thread is the {0}", myThread.Name);
39.

What is the usage of SequenceEqual() method in C#?

Answer»

The SequenceEqual() method is USED in C# to check whether two sequences are equal or not.

The following is an example:

using System; using System.Linq; class Example {    STATIC VOID Main()    {        string[] arr1 = { "one", "two", "three" };        string[] arr2 = { "one", "four", "five" };        bool res = arr1.SequenceEqual(arr2);        Console.WriteLine(res);    } }

The output:

False

Let us see another example:

using System; using System.Linq; class Example {    static void Main()    {        string[] arr1 = { "HTML", "CSS", "JAVASCRIPT" };        string[] arr2 = { "HTML", "CSS", "JavaScript" };        bool res = arr1.SequenceEqual(arr2);        Console.WriteLine(res);    } }

The output:

True
40.

When does the System.OutOfMemoryException occur in C#?

Answer»

The SYSTEM.OutOfMemoryException occurs when enough memory is not allocated.

Let US see an example:

USING System; using System.Text; namespace Application {   class Example {      static void Main(string[] args) {         try {            string deptname = "Tom";            string loc = "North";            StringBuilder s = new StringBuilder(deptname.Length, deptname.Length);            s.Append(deptname);            s.Insert(value: loc, INDEX: deptname.Length - 1, count: 1);         } catch (System.OutOfMemoryException e) {            Console.WriteLine("The following is the ERROR:");            Console.WriteLine(e);         }      }   } }

The example displays the Out Of Memory Exception:

The following is the error: System.OutOfMemoryException: Out of memory  at System.Text.StringBuilder.Insert (System.Int32 index, System.String value, System.Int32 count) [0x00065] in <902ab9e386384bec9c07fa19aa938869>:0  at Application.Example.Main (System.String[] args) [0x0002f] in <98ee8a52b3134b0799d382272292200f>:0
41.

How to get int value from enum?

Answer»

The int value can be obtained from enum by simply casting the enum. This process is successful because int is the default underlying type for enum. Similarly, for enums with different underlying types such as uint, ulong etc. the cast should be the type of enum.

A program that gets the int value from Enum is given as follows:

using System; public CLASS Demo {     public enum Fruits { Apple, MANGO, Orange, Peach, Melon }       public static void Main()   {      int num1 = (int)Fruits.Apple;        int num2 = (int)Fruits.Mango;        int num3 = (int)Fruits.Orange;        int num4 = (int)Fruits.Peach;        int num5 = (int)Fruits.Melon;        Console.WriteLine("Apple: " + num1);        Console.WriteLine("Mango: " + num2);        Console.WriteLine("Orange: " + num3);        Console.WriteLine("Peach: " + num4);        Console.WriteLine("Melon: " + num5);     } }

The OUTPUT of the above program is as follows:

Apple: 0 Mango: 1 Orange: 2 Peach: 3 Melon: 4
42.

How to intersect two lists in C#?

Answer»

Two lists can be intersected using the Enumerable.Intersect() method in C#. These methods provide the COMMON elements from both the lists as result. The namespace System.Linq is required for the Enumerable.Intersect() method.

A program that demonstrates the intersection of two lists is given as follows:

using System; using System.Collections.Generic; using System.Linq; class Demo {    public static VOID Main()    {        List&LT;int> list1 = new List<int>();        list1.Add(7);        list1.Add(1);        list1.Add(5);        list1.Add(9);        list1.Add(3);        List<int> list2 = new List<int>();        list2.Add(9);        list2.Add(6);        list2.Add(4);        list2.Add(1);        list2.Add(7);        var intersection = list1.Intersect(list2);        Console.WriteLine("The elements in the intersection of the two lists are:");        foreach (int i in intersection)        {            Console.WriteLine(i);        }    } }

The output of the above program is as follows:

The elements in the intersection of the two lists are: 7 1 9
43.

Traverse Singly Linked List in C#

Answer»

A singly linked list is a linear data structure in which each node contains the data as well as the POINTER or reference to the next node in the list. There is no pointer or reference to the previous node in the singly linked list.

A program that demonstrates traversal in a singly linked list is GIVEN as follows:

using System; NAMESPACE Demo {    class singlelinkedlist    {        private INT data;        private singlelinkedlist next;        public singlelinkedlist()        {            data = 0;            next = null;        }        public singlelinkedlist(int num)        {            data = num;            next = null;        }        public singlelinkedlist InsertLast(int num)        {            singlelinkedlist newnode = new singlelinkedlist(num);            if (this.next == null)            {                newnode.next = null;                this.next = newnode;            }           else            {                singlelinkedlist temp = this.next;                newnode.next = temp;                this.next = newnode;            }            return newnode;        }        public void traversal(singlelinkedlist node)        {            if (node == null)                node = this;            System.Console.WriteLine("The linked list elements are:");            while (node != null)            {                System.Console.WriteLine(node.data);                node = node.next;            }        }    }    class Program    {        static void Main(string[] args)        {            singlelinkedlist node1 = new singlelinkedlist(9);            singlelinkedlist node2 = node1.InsertLast(1);            singlelinkedlist node3 = node2.InsertLast(5);            singlelinkedlist node4 = node3.InsertLast(7);            singlelinkedlist node5 = node4.InsertLast(2);            node1.traversal(null);        }

The output of the above program is as follows:

The linked list elements are: 9 1 5 7 2
44.

How to Join two lists in C#?

Answer»

Two lists can be joined USING the AddRange() method. This method adds the elements of the specified list or collection at the END of the given list. The parameter of the AddRange() method is the list or collection whose elements are added at the end of the list. This  list or collection can have elements that are null but it itself cannot be null.

A program that DEMONSTRATES the join of two lists using the AddRange() method is given as follows:

using System; using System.Collections.Generic; class Demo {    public static void Main()    {        List<int> list1 = NEW List<int>();        list1.Add(7);        list1.Add(1);        list1.Add(5);        list1.Add(9);        list1.Add(3);        List<int> list2 = new List<int>();                list2.Add(1);        list2.Add(6);        list2.Add(4);        list1.AddRange(list2);        Console.WriteLine("The elements in list 1 are:");        foreach (int i in list1)        {            Console.WriteLine(i);        }    } }

The output of the above program is as follows:

The elements in list 1 are: 7 1 5 9 3 1 6 4
45.

Why do we use Singleton Class in C#?

Answer»

Singleton Class allow for single allocations and INSTANCES of data. It has a PRIVATE CONSTRUCTOR preventing class from being INSTANTIATED

46.

How to create custom exceptions in C#?

Answer»

Custom exceptions can be created by users as required by inheriting the exception class. Custom exceptions are usually created if the user needs are not met by any of the predefined exceptions.

A custom exception that is thrown if the age provided is negative is given as follows:

using System; namespace DEMO {   class PROGRAM   {      static void Main(string[] args)      {         Age OBJ = new Age();         try         {            obj.agePrint();         }         catch(GivenAgeIsNegativeException E)         {            Console.WriteLine("GivenAgeIsNegativeException: {0}", e.Message);         }      }   } } public class GivenAgeIsNegativeException: Exception {   public GivenAgeIsNegativeException(string message): base(message)   {   } } public class Age {   int age = -20;   public void agePrint()   {      if(age < 0)      {         throw (new GivenAgeIsNegativeException("ERROR!!! Age cannot be negative"));      }      else      {         Console.WriteLine("The age is: {0}", age);      }   } }

The output of the above program is as follows:

GivenAgeIsNegativeException: Error!!! Age cannot be negative
47.

What is the typical usage of OrderBy clause in C#?

Answer»

The OrderBy clause in C# allows the elements in the COLLECTION to be sorted in ascending order or DESCENDING order as required based on specified fields. Also multiple keys can be specified to make more secondary sort OPERATIONS if they are required. Also, the sorting using the OrderBy clause is in ascending order by default.

A program that demonstrates the OrderBy clause in C# is given as follows:

using System; using System.Linq; using System.Collections.Generic; public class Fruit { public string NAME { get; set; } } public class DEMO { public static void Main() { IList<Fruit> fruitList = new List<Fruit>() { new Fruit() { Name = "Orange" } , new Fruit() { Name = "Mango" } , new Fruit() { Name = "Apple" } , new Fruit() { Name = "Peach" } , new Fruit() { Name = "Guava" } , }; var sortAscendingOrder = from f in fruitList                   orderby f.Name                   select f; var sortDescendingOrder = from f in fruitList                   orderby f.Name descending                   select f; Console.WriteLine("Fruit Names in Ascending Order:"); foreach (var i in sortAscendingOrder)         Console.WriteLine(i.Name); Console.WriteLine("\nFruit Names in Descending Order:"); foreach (var i in sortDescendingOrder)         Console.WriteLine(i.Name); } }

The output of the above program is given as follows:

Fruit Names in Ascending Order: Apple Guava Mango Orange Peach Fruit Names in Descending Order: Peach Orange Mango Guava Apple
48.

Order array elements in C#

Answer»

The ARRAY elements in C# can be ordered using the Array.Sort() method. This method ORDERS the array elements and can modify the array in its place. Also, different types of array elements can be handled by Array.Sort() like integers, strings etc.

A program that demonstrates the ordering of array elements using Array.Sort() method is given as follows:

using System; NAMESPACE Demo {   public class Program   {      public static void Main(string[] args)      {        int[] arr = { 23, 67, 71, 9, 57, 35, 99, 85, 25, 1 };        Console.Write("The original array is: ");        foreach (int i in arr)        {            Console.Write(i + " " );        }        Array.Sort(arr);        Console.Write("\nThe sorted array is: ");        foreach (int i in arr)        {            Console.Write(i + " " );        }      }   } }

The output of the above program is given as follows:

The original array is: 23 67 71 9 57 35 99 85 25 1 The sorted array is: 1 9 23 25 35 57 67 71 85 99
49.

Sealed Classes in C#

Answer»

SEALED classes are used to restrict inheritance. In other words, sealed classes are those classes that cannot be extended and no class can be DERIVED from them. The sealed keyword is used to CREATE a sealed class in C#.

A program that demonstrates sealed classes in C# is given as follows:

using System; sealed class Product {    public int returnProduct(int num1, int num2)    {        return num1 * num2;    } } class Demo {    static void Main(string[] args)    {        Product obj = new Product();        Console.WriteLine("The product of 3 and 5 is: " + obj.returnProduct(3,5));    } }

The output of the above program is as follows:

The product of 3 and 5 is: 15

In the above program, the class Product is sealed class. This means that it cannot be INHERITED and an error will be generated if a class is derived from class Product.

50.

What is the role of Union() Method in C#?

Answer»

The Union() method PERFORMS the union of two collections. The resultant collection contains all the elements from both the collections but there are no duplicates. Also, The namespace System.Linq is required for the Union() method.

A program that demonstrates the union of two lists using the Union() method is given as follows:

using System; using System.Collections.Generic; using System.Linq; class DEMO {    PUBLIC static void Main()    {        List<int> list1 = new List<int>();        list1.Add(4);        list1.Add(1);        list1.Add(8);        list1.Add(2);        list1.Add(3);        List<int> LIST2 = new List<int>();        list2.Add(9);        list2.Add(1);        list2.Add(3);        list2.Add(7);        list2.Add(2);        var union = list1.Union(list2);        Console.WriteLine("The elements in the union of the two lists are:");        foreach (int i in union)        {            Console.WriteLine(i);        }    } }

The OUTPUT of the above program is as follows:

The elements in the union of the two lists are: 4 1 8 2 3 9 7