C# Interview Questions and answer


1.Can we declare multiple catch blocks to be execute?

Ans:No,Multiple catch blocks can't be execute  Once the proper catch code executed, the control is transferred to the finally block, and then the code that follows the finally block gets executed.


2.What is Constructor?
Ans:A constructor is a member function in a class that has the same name as its class. The constructor is automatically invoked whenever an object class is created. It constructs the values of data members while initializing the class.

3.Explain Jagged array
Ans:The Array which has elements of type array is called jagged Array. The elements can be of different dimensions and sizes. We can also call jagged Array as an Array of arrays.

4.What is ref and Out Parameter in c#?
Ans:Both are used to pass value as a reference.An argument passed as ref must be initialized before passing to the method whereas out parameter needs not to be initialized before passing to a method.

5.What is Serialization?
Ans:When we want to transport an object through a network, then we have to convert the object into a stream of bytes. The process of converting an object into a stream of bytes is called Serialization. For an object to be serializable, it should implement ISerialize Interface. De-serialization is the reverse process of creating an object from a stream of bytes.

6.Can we use This command with Static method?
Ans:We can't use 'This' in a static method because we can only use static variables/methods in a static method.

7.Give difference between const and read only.
Ans:Constant variables are declared and initialized at compile time. The value can't be changed afterward. Read-only is used only when we want to assign the value at run time.

8.What is an Interface?
Ans:An Interface is an abstract class which has only public abstract methods, and the methods only have the declaration and not the definition. These abstract methods must be implemented in the inherited classes.

9.What is Sealed class?
Ans:We create sealed classes when we want to restrict the class to be inherited. Sealed modifier used to prevent derivation from a class. If we forcefully specify a sealed class as base class, then a compile-time error occurs.

10.What is Method Overloading?
Ans:Method overloading is creating multiple methods with the same name with unique signatures in the same class. When we compile, the compiler uses overload resolution to determine the specific method to be invoke.

11.What is Difference between Array and Array List?
Ans:In an array, we can have items of the same type only. The size of the array is fixed when compared. To an arraylist is similar to an array, but it doesn't have a fixed size.

12.What is Difference between Interface ans Abstract class?
Ans.Interfaces have all the methods having only declaration but no definition. In an abstract class, we can have some concrete methods. In an interface class, all the methods are public. An abstract class may have private methods.

13.What is Delegate?
Ans:Delegates are same are function pointers in C++, but the only difference is that they are type safe, unlike function pointers. Delegates are required because they can be used to write much more generic type-safe functions.

14.Difference between Method Overloading and Method Overriding?
Ans:In method overriding, we change the method definition in the derived class that changes the method behavior. Method overloading is creating a method with the same name within the same class having different signatures.

15.What is Difference between struct and class?
Ans:Structs are value-type variables, and classes are reference types. Structs stored on the Stack causes additional overhead but faster retrieval. Structs cannot be inherited.





Ref and Out

What is Ref and Out Keyword?

Ref and out keywords in C# are used to pass arguments within a method or function. Both indicate that an argument/parameter is passed by reference.

Ref

The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Out

The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.


Please find below example for more clarity.I have used both ref and out parameter and also describe how it's work. you can also find different between ref and out comparing codes.


  class Proram
    {
        public static void Main() //Calling Method
        {
            int refval=0;//Must be define value
            int outval; //No need to define value

            GetNumberByRef(ref refval);
            Console.WriteLine("Values after called method using ref is {0} ", refval);

            GetNumberByOut(out outval);
            Console.WriteLine("Value after called method using our is {0} ", outval);

            Console.ReadLine();
        }
        public static void GetNumberByRef(ref int value)//Called Method
        {
            value = 101;//here it's optional to define value
        }
        public static void GetNumberByOut(out int value)//Called Mathod
        {
            value = 101;//You must define value here
           
        }
    }

Output
 
Values after called method using ref  is 101
Value after called method using our is  101


Note: Out and ref cannot be used in method with async mathod.

Async await in c#

What is async await in c#?


You might have already heard about asynchronous programming, either in C# or in some other language. In this page I will try to explain it to you, how to understand the concept easily, why and when we write asynchronous, the structure of async / await.

Asynchronous programming is very helpful in this condition. By using Asynchronous programming, the Application can continue with the other work that does not depend on the completion of the whole task.if any task depends on another task then next task will not execute until first task not completed.

Async and await are the code markers, which marks code positions from where the control should resume after a task completes.

We will get all the benefits of traditional Asynchronous programming with much less effort by the help of async and await keywords.

Let's take example so understand it properly

class Proram
    {
        public static void Main()
        {
       
            ProcessOne();
            IndependentProcess();//this process will run separately
            Console.ReadLine();
        }
        public async static void ProcessOne()
        {
            /*
             You can see that we mark DependedProcess method as await
             means untill DependedProcess will not complete next line will not called
            */
            await Task.Run(new Action(DependedProcess));
            Console.WriteLine("Process One Called");
        }
     
        public static void DependedProcess()
        {
            Thread.Sleep(2000);
            Console.WriteLine("Process Two Called");
        }
        public static void IndependentProcess()
        {
            Console.WriteLine("Independent Process");
        }
    }

Output:
Independent Process
Process Two Called
Process One Called

Summary: In above program you can see that Once DependentProcess method complete process after that next line of code will execute.while Independentprocess method will run separately this is called the Asynchronous programming.



















Operator Overloading

What is Operator overloading?

Opearator overloading is a concept which is related to polymorphisam. Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined.

Operator overloading gives the ability to use the same operator to do various operations

Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. similar to any other function, an overloaded operator has a return type and a parameter list.

Let's try to understand  Operator overloading (+)  by below example. using the + Operator you can do addition of two values and also contact two strings as below

 Obj 1 Operator     Obj 2 Result
 "C#"+ "Tutorial" C# Tutorial  
 15   +     20 35
Obj1       +    Obj2  can we do like that?? (let's do that with Operator Overloading) 


Please see below example for operator overloading and get to know that how we do addition of Obj1 + Obj2. run it on your machine to get more clerify.

    class Proram
    {
        public static void Main()
        {
            Course obj1 = new Course();
            obj1.Name = "C#";
            obj1.TotalMarks = 200;

            Course obj2 = new Course();
            obj2.Name = "Programming";
            obj2.TotalMarks = 300;

            Course obj3 = new Course();
            obj3 = obj1 + obj2;//Here operator overloading called.

            Console.WriteLine(obj3.Name + " - " + obj3.TotalMarks);
            Console.ReadLine();
        }
    }
    class Course
    {
        public string Name = "";
        public int TotalMarks = 0;

        public static Course operator +(Course Obj1, Course Obj2)
        {
            Course Obj3 = new Course();
            Obj3.Name = Obj1.Name + Obj2.Name;
            Obj3.TotalMarks = Obj1.TotalMarks + Obj2.TotalMarks;
            return Obj3;
        }
    }

Output
C#Programming - 500




Please visit given link for more details on Operator overloadig 

Sorted List - Generic

C# Sorted List

In c#, SortedList is a generic type of collection and it is used to store a collection of key/value pairs that are sorted by key based on the associated IComparer<T> implementation.

By default, the sortedlist will sort a key/value pairs in ascending order of the key and the sortedlist will allow storing only the strongly-typed objects i.e. the key/value pairs of the specified data type.

In c#, the sortedlist will allow us to store duplicate values but the keys must be unique and cannot be null to identify the values in sortedlist and the size of sortedlist will vary dynamically so you can add or remove elements from the sortedlist based on our application requirements.

C# includes two type of SortedList, generic SortedList and non-generic SortedList. Generic SortedList denotes with angel bracket: SortedList<TKey,TValue> where TKey is for type of key and TValue is for type of value. Non-generic type do not specify the type of key and values.


You can instantiate SortedList<TKey, TValue> by specifying type for key and value, as shown below.

Ex. SortedList<TKey, TValue> slist = new SortedList<TKey, TValue>();


Properties


 Property     Description
 Capacity     Gets or sets the number of elements that the SortedList<TKey,TValue> can store 
 Count Gets the total number of elements exists in the SortedList<TKey,TValue>.
 IsReadOnly Returns a boolean indicating whether the SortedList<TKey,TValue> is read-only.
 Item Gets or sets the element with the specified key in the SortedList<TKey,TValue>.
 Keys Get list of keys of SortedList<TKey,TValue>
 Values Get list of values in SortedList<TKey,TValue>.


Method

 Method         Description
Add  Add key-value pairs into SortedList<TKey, TValue>.
Remove Removes element with the specified key.
Remove At Removes element at the specified index.
Contains Key Checks whether the specified key exists in SortedList<TKey, TValue>.
Contains Value Checks whether the specified key exists in SortedList<TKey, TValue>.
Clear Removes all the elements from SortedList<TKey, TValue>.
Index Of Key Returns an index of specified key stored in internal array of SortedList<TKey, TValue>
Index Of Value
 Returns an index of specified value stored in internal array of SortedList<TKey,   TValue>
Try Get Value Returns true and assigns the value with specified key, if key does not exists then return false.


Example

 class CollectionExamples
    {
        public static void Main(String[] args)
        {

            SortedList<int, string> sl = new SortedList<int, string>();
            sl.Add(3, "Three");
            sl.Add(1, "One");
            sl.Add(2, "Two");
            sl.Add(4, null);

            foreach (var item in sl.Keys)
            {
                Console.WriteLine("Sorted List {0}", item);
            }
            Console.ReadLine();

        }
    }


Dictionary

C# Dictionary


  • The Dictionary<TKey, TValue> class is a generic collection class in the System.Collection.Generics namespace. TKey denotes the type of key and TValue is the type of TValue.
  • There is a non-generic collection called a Hashtable, which does the same thing, except that it operates on type object. However, you want to avoid the non-generic collections and use their generic counterparts instead
  • Dictionary cannot include duplicate or null keys, where as values can be duplicated or set as null. Keys must be unique otherwise it will throw a runtime exception.
  • The capacity of a Dictionary is the number of elements that Dictionary can hold.


Properties

 Property

 Description

 Count             Gets the total number of elements exists in the Dictionary<TKey,TValue>              .
 IsReadOnly Returns a boolean indicating whether the Dictionary<TKey,TValue> is read-only.
 Item Gets or sets the element with the specified key in the Dictionary<TKey,TValue>.
 Keys Returns collection of keys of Dictionary<TKey,TValue>.
 Values Returns collection of values in Dictionary<TKey,TValue>.

Methods


 Method     Description
 Add                Add key-value pairs in Dictionary<TKey, TValue> collection.                                                                  
 Remove     Removes the first occurrence of specified item from the Dictionary<TKey, TValue>.
 ContainsKey  Checks whether the specified key exists in Dictionary<TKey, TValue>.
 ContainsValue Checks whether the specified key exists in Dictionary<TKey, TValue>.
 Clear Removes all the elements from Dictionary<TKey, TValue>.
 TryGetValue Returns true and assigns the value with specified key, if key does not exists then return false.


Example

 public static void Main(String[] args)
   {
           
            Dictionary<int, string> _dictionary =  new Dictionary<int, string>();

            // Adding key/value pairs  
            _dictionary.Add(1, "Hello");
            _dictionary.Add(2, "This is");
            _dictionary.Add(3, "Blog for C#");

            _dictionary.Remove(1); //Remove value which key is 1

            Console.WriteLine("Is Key Exist?: {0}",_dictionary.ContainsKey(2));//Return True
            Console.WriteLine("Is Value Exist?: {0}", _dictionary.ContainsValue("This is"));//Return True
            foreach (KeyValuePair<int, string> ele1 in _dictionary)
            {
                Console.WriteLine("{0} and {1}",
                          ele1.Key, ele1.Value);
            }
            Console.ReadLine();

           
    }

List

 What is C# List<T>

  • List<T> class represents the list of objects which can be accessed by index. It comes under the System.Collection.Generic namespace
  • List class can be used to create a collection of different types like integers, strings etc. List<T> class also provides the methods to search, sort, and manipulate lists.
  • It is different from the arrays. A List<T> can be resized dynamically but arrays cannot.
  • List<T> class can accept null as a valid value for reference types and it also allows duplicate elements.
  • If the Count becomes equals to Capacity, then the capacity of the List increased automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.
  • List<T> class is the generic equivalent of ArrayList class by implementing the IList<T> generic interface.
  • This class can use both equality and ordering comparer.
  • List<T> class is not sorted by default and elements are accessed by zero-based index.
  • For very large List<T> objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the configuration element to true in the run-time environment.

Properties


 
Properties            
 Description 
 Capacity     Gets or sets the total number of elements the internal data structure can hold without resizing.
 Count Returns the total number of elements exists in the List<T>    
 Item Gets or sets the element at the specified index.


Methods


 Method     Usage    
 Add     Adds an element at the end of a List<T>.    
 AddRange     Adds elements of the specified collection at the end of a List<T>.        
 BinarySearch Search the element and returns an index of the element.
 Clear Removes all the elements from a List<T>.
 Contains Checks whether the speciied element exists or not in a List<T>
 Find Finds the first element based on the specified predicate function.
 ForEach Iterates through a List<T>.
 Remove<T>     Removes the first occurrence of a specific object from the List<T>.
 Remove All<T>            Removes all the elements that match the conditions defined by the specified predicate.
 Remove At(Int32) Removes the element at the specified index of the List<T>.
 RemoveRange(Int32,Int32)  Removes a range of elements from the List<T>.
 Reverse() Reverses the order of the elements in the List<T> or a portion of it.
 Sort()Sorts the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.    
 ToArray() Copies the elements of the List<T> to a new array.


Example:

class CollectionExamples
    {
        public static void Main(String[] args)
        {

            // Creating an List<T> of Integers 
            List<int> _List = new List<int>();

            // Adding elements to List 
            _List.Add(1);
            _List.Add(3);
            _List.Add(4);
            _List.Add(7);
            _List.Add(9);
            _List.Add(18);
            _List.Add(22);

            Console.WriteLine("Elements Present in List:\n");

            int p = 0;

            // Displaying the elements of List 
            foreach (int k in _List)
            {
                Console.Write("At Position {0}: ", p);
                Console.WriteLine(k);
                p++;
            }

            Console.WriteLine(" ");

            // removing the element at index 3 
            Console.WriteLine("Removing the element at index 3\n");
            _List.RemoveAt(4);

            int p1 = 0;

            // Displaying the elements of List 
            foreach (int n in _List)
            {
                Console.Write("At Position {0}: ", p1);
                Console.WriteLine(n);
                p1++;
            }
        }

Jagged Array

What is Jagged Array? Jagged array is called as "array of arrays". when you need a data inside your array element at that time you...