C# Interview Question and Answers with Example - Part 3


Below is top C# interview question and answers with examples for freshers and intermediate developers.



Views: 69

Give examples of generic collection.

Examples are shown below.
1) List
2) Dictionary
3) SortedList
4) Stack
5) Queue

What is difference between Array and ArrayList?

Array: 1) Array is strongly typed. This means that an array can store only specific type of items\elements.
2) Array stores fixed number of elements. Size of an Array must be specified at the time of initialization.
3) No need to cast elements of an array while retrieving because it is strongly type and stores specific type of items only.
4) Use static helper class Array to perform different tasks on the array. ArrayList: 1) ArrayList can store any type of items\elements.
2) ArrayList grows automatically and you don't need to specify size.
3) Items of ArrayList need to be cast to appropriate data type while retriving.
4) ArrayList itself includes various utility methods for various tasks.

What is difference between ArrayList and List?

ArrayList: 1) Found under system.collection namespace.
2) ArrayListArraylist is used to store any type of data there is no restriction that mean we can store integer or string or any object based on our requirements.
3) ArrayList resizes automatically as you add the elements.
4) ArrayList values must be cast to appropriate data types before using it.
5) ArrayList can contain multiple null and dulplicate items.
6) ArrayList can be accessed using foreach or for loop or indexer.
7) Provides Add, AddRange, Remove, RemoveRange, Insert, InsertRange, Sort, Reverse methods. Ex.

ArrayListmyArryList = new ArrayList();
myArryList.Add("One");
myArryList.Add(2);
myArryList.Add(3);
myArryList.Add(4.5f);
stringfirstElement = (string)myArryList[0];
intsecondElement = (int)myArryList[1];
intthirdElement = (int)myArryList[2];
floatfourthElement = (float)myArryList[3];

List: 1) Found under system.collection.generic namespace.
2) Generic List (List<T>)Generic lists are the type safe objects because it will store only specified datatype of elements.
3) List<T> here T means datatype i.e. either string, integer, etc.
4) List<T> stores elements of the specified type and it grows automatically.
5) List<T> can store multiple null and duplicate elements.
6) List<T> can be assigned to IList<T> or List<T> type of variable. It provides more helper method When assigned to List<T> variable 7) List<T> can be access using indexer, for loop or foreach statement.
8) LINQ can be use to query List<T> collection.
9) List<T> is ideal for storing and retrieving large number of elements. Ex.

List<int> myIntList = new List<int>();
myIntList.Add(10);
myIntList.Add(20);
myIntList.Add(30);
myIntList.Add(40);
List<string> myStringList = new List<string>();
myStringList.Add("one");
myStringList.Add("two");
myStringList.Add("three");
myStringList.Add("four");
myStringList.Add("four");
myStringList.Add(null);
myStringList.Add(null);
List<Student> myStudentList = new List<Student>();
myStudentList.Add(new Student());
myStudentList.Add(new Student());
myStudentList.Add(new Student());

What is difference between HashTable and Dictionary?

HashTable: 1) Found under system.collection namespace.
2) Hashtable stores key-value pairs of any datatype where the Key must be unique.
3) The Hashtable key cannot be null whereas the value can be null.
4) Hashtable retrieves an item by comparing the hashcode of keys. So it is slower in performance than Dictionary collection.
5) Hashtable uses the default hashcode provider which is object.GetHashCode(). You can also use a custom hashcode provider.
6) Use DictionaryEntry with foreach statement to iterate Hashtable. Ex.

Hashtablehashtable = new Hashtable();
hashtable.Add(1, "One");
hashtable.Add(2, "Two");
hashtable.Add(3, "Three");
hashtable.Add(4, "Four");
hashtable.Add(5, null);
hashtable.Add("Fv", "Five");
hashtable.Add(8.5F, 8.5);

Dictionary: 1) Found under system.collection.generic namespace.
2) Same as hashtable except that it is strongly type.
3) A Dictionary stores Key-Value pairs where the key must be unique.
4) Value can be null. Ex.

Dictionary<int,string> dict1 = new Dictionary<int,string>();
dict1.Add(1,"One");
dict1.Add(2,"Two");
dict1.Add(3,"Three");
dict1.Add(4,null);
//accessing dictionary
for (int i = 0; i < dict1.Count; i++)
{
Console.WriteLine("Key: {0}, Value: {1}", dict1.Keys.ElementAt(i), dict1[dict1.Keys.ElementAt(i)]);
}
//or
foreach (KeyValuePair<int,string> item in dict1)
{
Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}

The IDictionary type instance has one more overload for the Add() method. It accepts a KeyValuePair<tkey, tvalue> struct as a parameter. Ex.

IDictionary<int,string> dict2 = new Dictionary<int,string>();
dict2.Add(1, "One");
dict2.Add(new KeyValuePair<int,string>(2, "Two"));
dict2.Add(new KeyValuePair<int,string>(3, "Three"));
dict2.Add(new KeyValuePair<int,string>(4, null));
for (inti = 0; i< dict2.Count; i++)
{
Console.WriteLine("Key: {0}, Value: {1}", dict2.Keys.ElementAt(i), dict2[dict2.Keys.ElementAt(i)]);
}
//or
foreach (KeyValuePair<int,string> item in dict2)
{
Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}

What is difference between Stack and Queue?

Stack: 1) Can be found in generic and non-generic collection.
2) Stack stores the values in LIFO (Last in First out) style. The element which is added last will be the element to come out first.
3) Use the Push() method to add elements into Stack.
4) The Pop() method returns and removes elements from the top of the Stack. Calling the Pop() method on the empty Stack will throw an exception.
5) The Peek() method always returns top most element in the Stack. Ex.

// non generic
Stack myStack = new Stack();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
myStack.Push("test");
myStack.Push(null);
// generic 
Stack<int> myStack1 = new Stack<int>();
myStack1.Push(1);
myStack1.Push(2);

Queue: 1) Can be found in generic and non-generic collection.
2) The Queue stores the values in FIFO (First in First out) style. The element which is added first will come out First.
3) Use the Enqueue() method to add elements into Queue.
4) The Dequeue() method returns and removes elements from the beginning of the Queue. Calling the Dequeue() method on an empty queue will throw an exception.
5) The Peek() method always returns top most element. Ex.

// non generic
Queue queue = new Queue();
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue("Three");
queue.Enqueue(null);
// generic
Queue<int> queue2 = new Queue<int>();
queue2.Enqueue(1);
queue2.Enqueue(2);

What is Constructor in C#?

A constructor is special kind of method which gets automatically invoked when instance of class is created. A constructor is used to initialize private fields of the class when instance of class is created. Default constructor is automatically created by compiler, if you not created a constructor in the class. Key points to remember: A constructor with no parameter is called as default constructor.
Constructor doesn’t have any return type, not even void.
A class can have any number of constructors.
A static constructor can’t be parameterized constructor.
A class can have only one static constructor.

What are the types of Constructor?

Below is constructor types.
1) Default Constructor
2) Parameterized Constructor
3) Copy Constructor
4) Static Constructor
5) Private Constructor

What is Default Constructor?

A constructor without any parameter is called as default constructor. Default constructor initializes numeric fields to zero and string and object fields to null. Ex.

class Program
{
    int a;
    int b;
    public Program()
    {
        b = 10;
    }
    static void Main(string[] args)
    {
        Program p = new Program();
        Console.WriteLine(p.a); // output: 0  ,here default value is automatically initialized to zero
        Console.WriteLine(p.b); // output: 10  ,here we have initialized with value 10
        Console.ReadKey();
    }
}

What is Parameterized Constructor?

A constructor with at least one parameter is called as parameterized constructor. Using parameterized constructor we can override default values with own values. Ex.

class Program
{
    int a;
    int b;
    public Program(int p, int q)
    {
        a = p;
        b = q;
    }
    static void Main(string[] args)
    {
        Program p = new Program(10, 20);
        Console.WriteLine(p.a); // output: 10  
        Console.WriteLine(p.b); // output: 20 
        Console.ReadKey();
    }
}

Parameterized and Default Constructor together

Here in below example we have used parameterized and default constructor together. But, while creating object, we are calling parameterized constructor to initialized value of variable ‘a’ and ‘b’. While debugging application, default constructor is not called and still value of variable ‘c’ is initialized to ‘zero’. Ex.

class Program
{
    int a;
    int b;
    int c;
    public Program(int p, int q)
    {
        a = p;
        b = q;
    }
    public Program()
    {
        a = 30;
        b = 40;
        c = 50;
    }
    static void Main(string[] args)
    {
        Program p = new Program(10, 20);
        Console.WriteLine(p.a); // output: 10  
        Console.WriteLine(p.b); // output: 20 
        Console.WriteLine(p.c); // output: 0 
        Console.ReadKey();
    }
}

What is Copy Constructor?

C# doesn’t provide a copy constructor for objects, but you can write one yourself.
A copy constructor is a type of parameterized constructor where we pass parameter of same class type. Copy constructor is used to initialize new instance by using existing instance. Ex.

class Program
{
    int a;
    int b;
    public Program(int p, int q)
    {
        a = p;
        b = q;
    }
    public Program(Program p)
    {
        a = 10 + p.a; // adding 10
        b = 10 + p.b;
    }
    static void Main(string[] args)
    {
        Program p1 = new Program(10, 20);
        Console.WriteLine(p1.a + " and " + p1.b); // output: 10 and 20
        // here passing existing object p1
        Program p2 = new Program(p1);
        Console.WriteLine(p2.a + " and " + p2.b); // output: 20 and 30
        Console.ReadKey();
    }
}

What is Static Constructor?

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
A static constructor does not take access modifiers or have parameters. Key Points: A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
A static constructor cannot be called directly.
The user has no control on when the static constructor is executed in the program.
A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.
Ex.

class Program
{
    public Program()
    {
        Console.WriteLine("Default constructor is called");
    }
    static Program()
    {
        Console.WriteLine("Static constructor is called only once and also before first instance is created");
    }
    static void Main(string[] args)
    {
        // here static constructor is called before object creation
        Program p1 = new Program(); // default constructor is called
        Program p2 = new Program(); // default constructor is called again
        Console.ReadKey();
    }
}
// Output:
// Static constructor is called only once and also before first instance is created
// Default constructor is called
// Default constructor is called

What is Private Constructor?

We will update soon.....

What is extension method in C#?

Extension method is used to add or extend functionality of own class or in-built classes of .net. Here, in below example we have created a static class MyStaticClass and static method RemoveDuplicateChars which removes duplicate characters of specified string. This method can be applied on string data type.

Ex:
class Program
{
    static void Main(string[] args)
    {
        string output = "aabbcdxbdcx";
        Console.WriteLine("String without duplicates char: " + output.RemoveDuplicateChars());
        Console.ReadKey();
    }
}
public static class MyStaticClass
{
    public static string RemoveDuplicateChars(this string inputString)
    {
        string newString = string.Empty;
        var unique = new HashSet<char>(inputString);
        foreach (char c in unique)
        {
            newString += c.ToString();
        } 
        return newString;
    }
}
// OUTPUT:
abcdx

What is difference between int.Parse and Convert.ToInt32?

1) Both are used to convert string to number in C#.
2) Convert.ToInt32 returns 0 when argument is null where as int.Parse returns Argument Null Exception.

What is difference between int.Parse and int.TryParse?

1) Both are used to convert string to number in C#.
2) int.Parse method throws excepton if string is not valid integer.
3) int.TryParse returns true along with integer value as out parameter if string is valid number.
4) int.TryParse returns false and integer value to 'zero' as out parameter if string is not a valid number.

What is implicit and explicit conversion?

Implicit conversion:
1) Implicit conversion is done automatically by compiler when we assign lower data type to higher data type.
2) There is no loss of data while conversion.
ex.
int a = 10;
double b = a;
Explicit conversion:
1) When we assign higer data type to lower data type then explicit conversion is required.
2) There may be loss of data while conversion.
ex.
//successful conversion
double a = 10;
int b = (int)a; // output : 10

//failed conversion
double a = 1023545788555;
int b = (int)a; // output : -2147483648 it returns min value of int

What is difference between int and int32?

Both are same. int is an alias for Int32.

Difference between bool and boolean in C#

bool is an alias for the Boolean class.

What is difference between signed int and un-signed int?

1) signed int stores negative as well as positive value.
Ex.
sign int (32 bit):
int a = -2147483648; // min value;
int b = 2147483647; // max value;

2) un-signed int only stores positive value.
Ex.
unsign int (32 bit):
uint a = 0; // min value;
uint b = 4294967295; // max value;

What are different types of comment in C#?

There are 3 types of comment in C#.
1) Single line // single line comment
2) Multiline /*This is multiline commentt*/
3) Xml comment
/// <summary>
/// about class definition.
///</summary>

What is difference between method parameter and method argument?

When we declare method with some input or output parameter then it is called as method parameter.
When we actual pass the data to the method using input or output then it is called as method argument.
Basically value of parameter is called as argument.

Which version of C# is supported in visual studio 2013?

C# version 5.0 in .net framework 4.5
C# version 6.0 in .net framework 4.6

What are the types of parameter that can be passed to a method?

passing value type, passing ref type, passing out type, passing using [params array].

What is delegate in C#?

A delegate is a type safe pointer to a function.
This means delegate signature should match with method signature that are being reference.
Delegate is a reference type.
Delegates are mostly used in call back mechanism.
Many methods can be registered with delegate and can be executed at run time when respective event occurs.



Views: 69