Tuesday, 20 March 2018

C# Interview Questions



C# 2.0 Features
          1. Generics
          2. Method parameters and Constraints
          3. Factories
          4. Partial Types
          5. Anonymous method
          6. Async Tasks
          7. Nullable Types
          8. Delegates

C# 3.0 Features
          1. Object and collection Initializers
          2. Implicitly typed local variables
          3. Auto Implemented Properties
          4. Anonymous Types
          5. Extension Methods
          6. Query Expressions
          7. Lambda Expressions
          8. Expression Trees

C# 4.0 Features
          1. Dynamic Binding
          2. Named and optional Arguments



Generics
Generics were added to version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.
Overview
·        Use generic types to maximize code reuse, type safety, and performance.
·        The most common use of generics is to create collection classes.
·        The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible instead of classes such as ArrayList in the System.Collections namespace.
·        You can create your own generic interfaces, classes, methods, events and delegates.
·        Generic classes may be constrained to enable access to methods on particular data types.
·        Information on the types that are used in a generic data type may be obtained at run-time by using reflection.

Example
using System;
using System.Collections.Generic;

namespace GenericApplication {
   public class MyGenericArray<T> {
      private T[] array;
     
      public MyGenericArray(int size) {
         array = new T[size + 1];
      }
      public T getItem(int index) {
         return array[index];
      }
      public void setItem(int index, T value) {
         array[index] = value;
      }
   }
   class Tester {
      static void Main(string[] args) {
        
         //declaring an int array
         MyGenericArray<int> intArray = new MyGenericArray<int>(5);
        
         //setting values
         for (int c = 0; c < 5; c++) {
            intArray.setItem(c, c*5);
         }
        
         //retrieving the values
         for (int c = 0; c < 5; c++) {
            Console.Write(intArray.getItem(c) + " ");
         }
        
         Console.WriteLine();
        
         //declaring a character array
         MyGenericArray<char> charArray = new MyGenericArray<char>(5);
        
         //setting values
         for (int c = 0; c < 5; c++) {
            charArray.setItem(c, (char)(c+97));
         }
        
         //retrieving the values
         for (int c = 0; c< 5; c++) {
            Console.Write(charArray.getItem(c) + " ");
         }
         Console.WriteLine();
        
         Console.ReadKey();
      }
   }
}
         



Partial Types
C# version 2.0 introduced partial types. This new concept permits the code in a single class, structure or interface to be split into more than one code file. Each constituent part of the type is combined during the compilation process.



Anonymous methods
The concept of anonymous method was introduced in C# 2.0. An anonymous method is inline unnamed method in the code. It is created using the delegate keyword and doesn’t required name and return type. Hence we can say, an anonymous method has only body without name, optional parameters and return type. An anonymous method behaves like a regular method and allows us to write inline code in place of explicitly named methods.
delegate int MathOp(int a, int b);
class Program
{
//delegate for representing anonymous method
delegate int del(int x, int y);

static void Main(string[] args)
{
//anonymous method using delegate keyword
del d1 = delegate(int x, int y)
{
return x * y;
};

int z1 = d1(2, 3);

Console.WriteLine(z1);
}
}
//output:
6

Key points about anonymous method
1.     A variable, declared outside the anonymous method can be accessed inside the anonymous method.
2.     A variable, declared inside the anonymous method can’t be accessed outside the anonymous method.
3.     We use anonymous method in event handling.
4.     An anonymous method, declared without parenthesis can be assigned to a delegate with any signature.
5.     Unsafe code can’t be accessed within an anonymous method.
6.     An anonymous method can’t access the ref or out parameters of an outer scope.




Async Tasks
Asynchronous operation means that the operation runs independent of main or other process flow. In general c# program starts executing from the Main method and ends when the Main method returns. In between all the operations runs sequentially one after another. One operation must wait until its previous operation finishes. Let see the following.
static void Main(string[] args)
        {
           DoTaskOne();
           DoTaskTwo();
        }

Method “DoTaskTwo” would not be started until “DoTaskOne” finishes. In other words method “DoTaskOne” blocks the execution as long it takes to finish.
In asynchronous programming a method is called that runs in the background and the calling thread is not blocked. After calling the method the execution flow immediately backs to calling thread and performs other tasks. Normally it uses Thread or Task (We will discuss Thread and Task in detail later).
In our case if we run the “DoTaskOne” asynchronously, after calling the “DoTaskOne” method, execution flow immediately backs to Main method and start “DoTaskTwo”.

“async” and “await” keywords

.NET framework introduced two new keywords to perform asynchronous programing: “async” and “await”. To use “await” keyword within a method we need to declare the method with “async” modifier. “await” keyword is used before calling an asynchronous method. “await” keyword suspends further execution of the method and control is return to the calling thread. See the example:
private int CountCharacters()
        {
            int count = 10;
            using (StreamReader reader = new StreamReader("C:\\Test\\TestFile.txt"))
            {
                string content = reader.ReadToEnd();
                count = content.Length;
                Thread.Sleep(5000);
            }
            return count;           
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            label1.Text = "Processing";
            Task<int> task = new Task<int>(CountCharacters);
            task.Start();
            int count = await task;
            label1.Text = count.ToString();     
        }

Parallel programming

Parallel computing is a type of computation in which many calculations or the execution of processes are carried out simultaneously.[1] Large problems can often be divided into smaller ones, which can then be solved at the same time. There are several different forms of parallel computing: bit-levelinstruction-leveldata, and task parallelism. Parallelism has long been employed in high-performance computing, but it's gaining broader interest due to the physical constraints preventing frequency scaling.[2] As power consumption (and consequently heat generation) by computers has become a concern in recent years,[3] parallel computing has become the dominant paradigm in computer architecture, mainly in the form of multi-core processors.[4]
Parallel computing is closely related to concurrent computing—they are frequently used together, and often conflated, though the two are distinct: it is possible to have parallelism without concurrency (such as bit-level parallelism), and concurrency without parallelism (such as multitasking by time-sharingon a single-core CPU).[5][6] In parallel computing, a computational task is typically broken down into several, often many, very similar subtasks that can be processed independently and whose results are combined afterwards, upon completion. In contrast, in concurrent computing, the various processes often do not address related tasks; when they do, as is typical in distributed computing, the separate tasks may have a varied nature and often require some inter-process communication during execution.

Difference between Abstract class and Interface
  • A class can implement any number of interfaces but a subclass can at most use only one abstract class.
  • An abstract class can have non-abstract methods (concrete methods) while in case of interface all the methods has to be abstract.
  • An abstract class can declare or use any variables while an interface is not allowed to do so.
  • In an abstract class all data member or functions are private by default while in interface all are public, we can’t change them manually.
  • In an abstract class we need to use abstract keyword to declare abstract methods while in an interface we don’t need to use that.
  • An abstract class can’t be used for multiple inheritance while interface can be used as multiple inheritance.
  • An abstract class use constructor while in an interface we don’t have any type of constructor.

Difference between const and read only
Constant (const) and Readonly (readonly) both looks like same as per the uses but they have some differences: 

Constant is known as “const” keyword in C# which is also known immutable values which are known at compile time and do not change their values at run time like in any function or constructor for the life of application till the application is running.

Readonly is known as “readonly” keyword in C# which is also known immutable values and are known at compile and run time and do not change their values at run time like in any function for the life of application till the application is running. You can assay their value by constructor when we call constructor with “new” keyword.

What are the differences between IEnumerable and IQueryable?

Answer: 

Before the differences learn what is IEnumerable and IQueryable.

IEnumerable:

Is the parent interface for all non-generic collections in System.Collections namespace like ArrayList, HastTable etc. that can be enumerated. For the generic version of this interface as IEnumerable<T> which a parent interface of all generic collections class in System.Collections.Generic namespace like List<> and more. 

IQueryable:

As per MSDN IQueryable interface is intended for implementation by query providers. It is only supposed to be implemented by providers that also implement IQueryable<T>. If the provider does not also implement IQueryable<T>, the standard query operators cannot be used on the provider's data source.

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed. The definition of "executing an expression tree" is specific to a query provider. For example, it may involve translating the expression tree to an appropriate query language for the underlying data source. Queries that do not return enumerable results are executed when the Execute method is called.

ASP.NET

What is the Constructor Chaining in C#?

Answer: constructor chaining is a way to connect two or more classes in a relationship as Inheritance, in Constructor Chaining every child class constructor is mapped to parent class Constructor implicitly by base keyword so when you create an instance of child class to it’ll call parent’s class Constructor without it inheritance is not possible.

Difference between Equality Operator (==) and Equals() Method in C#.

Answer: 

Both the == Operator and the Equals() method are used to compare two value type data items or reference type data items. The Equality Operator (==) is the comparison operator and the Equals() method compares the contents of a string. The == Operator compares the reference identity while the Equals() method compares only contents. Let’s see with some examples.

In this example we assigned a string variable to another variable. A string is a reference type and in the following example, a string variable is assigned to another string variable so they are referring to the same identity in the heap and both have the same content so you get True output for both the == Operator and the Equals() method.
1.     using System;  
2.     namespace ComparisionExample {  
3.         class Program {  
4.             static void Main(string[] args) {  
5.                 string name = "sandeep";  
6.                 string myName = name;  
7.                 Console.WriteLine("== operator result is {0}", name == myName);  
8.                 Console.WriteLine("Equals method result is {0}", name.Equals(myName));  
9.                 Console.ReadKey();  
10.         }  
11.     }  
12. }  

What is Virtual Method in C#?


A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived the class. It is used when a method's basic functionality is the same but sometimes more functionality is needed in the derived class. A virtual method is created in the base class that can be overridden in the derived class. We create a virtual method in the base class using the virtual keyword and that method is overridden in the derived class using the override keyword.

When a method is declared as a virtual method in a base class then that method can be defined in a base class and it is optional for the derived class to override that method. The overriding method also provides more than one form for a method. Hence it is also an example for polymorphism.

When a method is declared as a virtual method in a base class and that method has the same definition in a derived class then there is no need to override it in the derived class. But when a virtual method has a different definition in the base class and the derived class then there is a need to override it in the derived class.

When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.

Virtual Method
1.     By default, methods are non-virtual. We can't override a non-virtual method.
2.     We can't use the virtual modifier with the static, abstract, private or override modifiers.
What is Serialization?

Answer: 

Serialization means saving the state of your object to secondary memory, such as a file.

Suppose you have a business layer where you have many classes to perform your business data.

Now suppose you want to test whether your business classes give the correct data out without verifying the result from the UI or from a database. Because it will take some time to process.

SO what you will you do my friend?

Here comes Serialization. You will serialize all your necessary business classes and save them into a text or XML file.

on your hard disk. So you can easily test your desired result by comparing your serialized saved data with.

your desired output data. You can say it is a little bit of autonomic unit testing performed by the developer.

There are three types of serialization:
1.     Binary serialization (Save your object data into binary format).
2.     Soap Serialization (Save your object data into binary format; mainly used in network related communication).
3.     XmlSerialization (Save your object data into an XML file).

What is the use of Using statement in C#?


The .Net Framework provides resource management for managed objects through the garbage collector - You do not have to explicitly allocate and release memory for managed objects. Clean-up operations for any unmanaged resources should performed in the destructor in C#. To allow the programmer to explicitly perform these clean-up activities, objects can provide a Dispose method that can be invoked when the object is no longer needed. The using statement in C# defines a boundary for the object outside of which, the object is automatically destroyed. The using statement is excited when the end of the "using" statement block or the execution exits the "using" statement block indirectly, for example - an exception is thrown. The "using" statement allows you to specify multiple resources in a single statement. The object could also be created outside the "using" statement. The objects specified within the using block must implement the IDisposable interface. The framework invokes the Dispose method of objects specified within the "using" statement when the block is exited. 

Delegates
C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.
Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegateclass.

using System;

delegate int NumberChanger(int n);
namespace DelegateAppl {
  
   class TestDelegate {
      static int num = 10;
     
      public static int AddNum(int p) {
         num += p;
         return num;
      }
      public static int MultNum(int q) {
         num *= q;
         return num;
      }
      public static int getNum() {
         return num;
      }
      static void Main(string[] args) {
         //create delegate instances
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);
        
         //calling the methods using the delegate objects
         nc1(25);
         Console.WriteLine("Value of Num: {0}", getNum());
         nc2(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}


No comments:

Post a Comment

Azure Service Bus Queue , Table - Send, Read

using Microsoft.ServiceBus.Messaging; using System; using System.Collections.Generic; using System.Linq; using System.Text; ...