0% found this document useful (0 votes)
40 views34 pages

Interview QSNS (Repaired)

Uploaded by

praveen kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views34 pages

Interview QSNS (Repaired)

Uploaded by

praveen kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

C# Questions

1. Interfaces

 We create interfaces using interface keyword. Just like classes interfaces also contains
properties, methods, delegates or events, but only declarations and no implementations.

 It is compile time error to provide implementations for any interface member.

 Interface members are public by default, and they don’t allow explicit access modifiers.

 Interfaces cannot contain fields (ex: int ID; string Name;)

 If a class or struct inherits from an interface, it must provide implementation for all interface
members. Otherwise we get a compile error.

 A class or struct can inherit from more than one interface at the same time, but whereas, a
class cannot inherit from more than one class at the same time.

 Interfaces can inherit from other interfaces. A class that inherits this interface must provide
implementation for all interface members in the entire interface inheritance chain.

 We cannot create an instance of an interface, but an interface reference variable can point to a
derived class object.

 Interface Naming convention: Interface names are prefixed with capital I

interface ICustomer1
{
void Print1();
}

interface ICustomer2 : ICustomer1


{
void Print2();
}

public class Customer : ICustomer2


{
public void Print1()
{
Console.WriteLine("Print1");
}

public void Print2()


{
Console.WriteLine("Print2");
}
}

public class program


{
public static void main()
{
Customer cst = new Customer();
cst.Print1();
cst.Print2();
}

2. Abstract Class

 The abstract keyword is used to create abstract classes.


 An abstract class is incomplete and hence cannot be instantiated.
 An abstract class can only be used as base class.
 An abstract class cannot be sealed.
 An abstract class may contain abstract members (methods, properties, indexers, and events)
but not mandatory.
 A non-abstract class derived from an abstract class must provide implementations for all
inherited abstract members.
If a class inherits an abstract class, there are 2 options available for that class.
Option 1: Provide implementation for all the abstract members inherited from the base abstract class.
Option 2: If the class does not wish to provide implementation for all the abstract members inherited
from the abstract class, then the class has to be marked as abstract.

We would create an abstract class, when we want to move the common functionality of 2 or more
related classes into a base class and when, we don’t want the base class to be instantiated.

Ex:

Public abstract class BaseEmployee


{
Public int ID { get; set;}
Public string FirstName {get; set;}
Public string LastName {get; set;}
Public string GetFullName(){
Return this.Firstname + “ ” + this.LastName;
}

Public abstract int GetMonthlySalary();

}
Public class ContractEmployee : BaseEmployee{
Public int HourlyPay {get; set;}
Public int TotalPay {get; set;}
Public override int GetMonthlySalary(){
Return this.TotalHours*this.HourlyPay;
}

Public class FullTimetEmployee : BaseEmployee{


Public int AnnualSalary{get; set;}

Public override int GetMonthlySalary(){


Return this.AnnualSalary / 12;;
}

Abstract Classes Interfaces


Can have implementations for some of its Only declarations and no implementations for its
members(Methods) members.

Can have fields Cannot have fields.

An abstract class can inherit from another An interface can inherit from another interface
abstract class or another interface. only and cannot inherit from an abstract class or
any other classes.

A class cannot inherit from multiple classes at the A class can inherit from multiple interfaces at the
same time. same time.

Abstract classes can have access modifiers. Interface member cannot have access modifiers.

Abstract class members are private by default. Interface members are public by default, and they
don’t allow explicit access modifiers.

An abstract class is incomplete and hence cannot We cannot create an instance of an interface, but
be instantiated, but abstract class reference an interface reference variable can point to a
variable can be point to a derived class object. derived class object.

Can only be used as base class. Can only be used as base type.
3. Inheritance

Inheritance is one of the most important concepts in object-oriented programming.

We will specify all the common fields, properties, methods in the base class, which allows reusability.
These base class members will be used by derived class.

This provides an opportunity to reuse the code functionality and speeds up implementation time.

C# supports only single class inheritance. And supports multi-level class inheritance but not multiple
class inheritance. And C# supports multiple interface inheritance.

Base classes are automatically instantiated before the derived classes. Parent class constructor
executes before the child class constructor.

4. Does .NET support multiple inheritance? Why?


C# as well as Java languages don't support multiple inheritance because of the diamond
problem.
The diamond problem is an ambiguity that arises when two classes B and C inherit from A, and
class D inherits from both B and C. If a method in D calls a method defined in A (and does not
override the method), and B and C have overridden that method differently, then from which
class does it inherit: B, or C?

Ex:
public class Employee
{
public virtual void DoWork()
{
//Do work
}
}

public class Manager:Employee


{
public override void DoWork()
{
//Manager's implementation of do work
}
}
public class Developer : Employee
{
public override void DoWork()
{
//Deveoper's implementation of do work
}
}

public class JuniorDeveloper:Manager, Developer// Compile Time Error :Cannot have multiple
base classes but assume that it were possible
{

5. Constant & Read Only Variables

Constant: Compile time constant. Const will be used for absolute constant values [i.e. value is
same globally]. Value should be provided for constant variable during the declaration itself. Value
cannot be changed once it is assigned. By default, constant is static.

Readonly: Run time constant. Value can set during runtime when the application initializes or
constructor fires.

Class program
{
Public static const int cmToMeters = 100; //Compile time constant
Public static readonly double PI =3.14; //Run time constant

Public static Program(){


PI=3.1;
}
Static void Main(string[] args){

}
}

Constant Readonly
Constant can have value assigned at the Readonly fields value can be assigned at
declaration time only. declaration time or in the constructor level.

For accessing the constant variable we can use Need to create an instance for accessing the
[ClassName].[VariableName] Readonly field.

Value will be known at compile time. Values will be known at runtime.

Access modifiers Public, Private, Protected and internal can be used with constant and Readonly
keywords.
6. String Vs String Builder
String Stringbuilder
Namespace: System.String Namespace: System.Text.StringBuilder

String txt=”C#”; StringBuilder txt = new StringBuilder(“C#”);


txt+= “Video”; txt.Append(“Video”);
Txt+= “tutorials”; txt.Append(“tutorials”);
txt = txt.ToString();
Strings are Immutable. That means, value of the StringBuilders are Mutable. This means value can
object cannot be changed. So that, a new object be changed within a single object for every
will be created for every manipulation manipulation of that string without creating new
(concatenation) of that string and only recent objects. So, this offers better performance.
object will be in use and remaining all are useless.
Due to this, much memory will be consumed and
performance will be degraded.

This unused memory will be released only when


GC runs.

Polymorphism:

 Polymorphism is one of the primary pillars of Object Oriented Programming.


 Polymorphism allows us to invoke derived class methods through a base class reference during
runtime.
 In the base class the method is declared virtual, and in the derived class we override the same
method.
 The virtual keyword indicates, the method can be overridden in any derived class.
 Polymorphism is the concepts of OOPS which includes method overriding and method
overloading. Virtual and Override keyword are used for method overriding and new keyword
is used for method hiding.

7. Overloading:

Method overloading allows a class to have multiple methods with the same name, but with a
different signature. So in C#, functions can be overloaded based on the number, type (int , float
etc) and kind(Value, Ref or Out) of parameters.

The signature of a method does not include the return type and params modifier. So, it is not
possible to overload a function, just based on the return type or params modifier.
8. Overriding

 Creating a method in derived class with same signature as a method in base class is called as
method overriding.

 Same signature means methods must have same name, same number of arguments and same
type of arguments.

 When derived class needs a method with same signature as in base class, but wants to execute
different code than provided by base class then method overriding will be used.

 To allow the derived class to override a method of the base class, C# provides two
options, virtual methods and abstract methods.

EX:

using System;

namespace methodoverriding
{
class BaseClass
{
public virtual string YourCity()
{
return "New York";
}
}

class DerivedClass : BaseClass


{
public override string YourCity()
{
return "London";
}
}

class Program
{

static void Main(string[] args)


{
DerivedClass obj = new DerivedClass();
string city = obj.YourCity();
Console.WriteLine(city);
Console.Read();
}
}
}
9. Dynamic VS Var keywords in C#
Dynamic:
Late bounded. Methods and properties everything will be checked during run time.

We can store any type of value in the dynamic data type variable. Type checking for these types of
variables takes place at run-time.
Syntax for declaring a dynamic type is −

dynamic <variable_name> = value;

For example,

dynamic d = 20;

Var : Early bounded. It is statically checked. It is checked during compiled time itself. In compile
time the left hand side data type will be figured out by comparing the right hand side data.

10. What is the difference between dynamic type variables and object type variables?

Dynamic types are similar to object types except that type checking for object type variables takes
place at compile time, whereas that for the dynamic type variables takes place at run time.

11. Value type Vs Reference type Variables


Value Types
Variables that store data are called value types. Value types are stored on stack.
They contain the actual values. eg- int, enum, structs.

Reference Types
Variables that store reference to actual data are called Reference types. Reference types
stored on heap but contain the address on heap.
eg- class, interface, delegate, string, object, Array

Value Type Reference Type


They are stored on stack They are stored on heap
Contains actual value Contains reference to a value
Cannot contain null values. However Can contain null values.
this can be achieved by nullable types
Value type is popped on its own from Required garbage collector to free
stack when they go out of scope. memory.
Memory is allocated at compile time Memory is allocated at run time

Stack Heap
Values are stored on one Values are stored in random order. like
another like a stack. dumped into a huge space
Used for value type Used for reference types

12. Singleton
 Singleton comes under creational design pattern category.
 No client can create instance of object from outside.
 Only one instance of class will be created and shared among all clients.
 Define constructor with private access modifier.
 Define all methods and public properties as static.

Ex:

Public class SingletonDBclass

Private static SqlConnection con;

Private SingletonDBclass(){ //private constructor.

Public static SqlConnection GetConnection(){

Con =new SqlConnection();

return con;

Calling method without creating new instance.

SingletonDBclass. GetConnection();

13. Partial Classes


It is possible to split the definition of a class or a struct, an interface or a method over two or more
source files. Each source file contains a section of the type or method definition, and all parts are
combined when the application is compiled.

When working on large projects, spreading a class over separate files enables multiple programmers
to work on it at the same time.

File1.cs

public partial class Employee


{
public void DoWork()
{
}
}

File2.cs
public partial class Employee
{
public void GoToLunch()
{
}
}

Points that you should be careful about partial classes

There are some points that you should be when you are developing a partial class in your application.

1. You need to use partial keyword in each part of partial class.

2. The name of each part of partial class should be the same but source file name for each part of partial
class can be different.

3. All parts of a partial class should be in the same namespace.

4. Each part of a partial class should be in the same assembly or DLL, in other words you can't create a
partial class in source files of a different class library project.

5. Each part of a partial class has the same accessibility.

6. If you inherit a class or interface on a partial class then it is inherited on all parts of a partial class.

7. If a part of a partial class is sealed, then the entire class will be sealed.

8. If a part of partial class is abstract, then the entire class will be an abstract class.

9. The partial modifier is not available on delegate or enumeration declarations.

Partial Methods
A partial class or struct may contain a partial method. One part of the class contains the signature of the
method. An optional implementation may be defined in the same part or another part. If the
implementation is not supplied, then the method and all calls to the method are removed at compile
time.

A partial method declaration consists of two parts: the definition, and the implementation. These may be
in separate parts of a partial class, or in the same part.
Ex: -
// Definition in file1.cs (part1)
partial void onNameChanged();

// Implementation in file2.cs (part2)


partial void onNameChanged()
{
// method body
}

Notes:
 Partial method declarations must begin with the contextual keyword partial and the method must
return void.
 Partial methods can have ref but not out parameters.
 Partial methods are implicitly private, and therefore they cannot be virtual.
 Partial methods cannot be extern, because the presence of the body determines whether they are
defining or implementing.
 Partial methods can have static and unsafe modifiers.
 Partial methods can be generic. Constraints are put on the defining partial method declaration,
and may optionally be repeated on the implementing one. Parameter and type parameter names
do not have to be the same in the implementing declaration as in the defining one.
 You can make a delegate to a partial method that has been defined and implemented, but not to
a partial method that has only been defined.

14. Anonymous types in C#


 Anonymous types provide a convenient way to encapsulate a set of read-only properties into a
single object without having to explicitly define a type first. The type name is generated by the
compiler and is not available at the source code level.
 We can create anonymous types by using the new operator together with an object initializer.
The implicitly typed variable- var is used to hold the reference of anonymous types.

var v = new { Amount = 108, Message = "Hello" };

 We can create an array of anonymously typed elements as shown below.


var anonArray = new[] { new { name = "apple", diam = 4 }, new { name = "grape", diam = 1 }};

 Anonymous types have been introduced to support one of the most useful features called LINQ.
It's most useful when you are querying collection of object using LINQ query and you want to
return only a few of its properties.

 The anonymous type is very useful when we want to shape the result in your desired form like
this:

 var result = from book in Books


 where book.Price > 200
 orderby book.IssueDate descending
 select new
 {
 Name = book.Name,
 IssueNumber = "#" + book.Issue
 };

Points to Remember:
 Anonymous type can be defined using the new keyword and object initializer syntax.
 The implicitly typed variable- var, is used to hold an anonymous type.
 Anonymous type is a reference type and all the properties are read-only.
 The scope of an anonymous type is local to the method where it is defined.
 Usually, you cannot pass an anonymous type to another method; however, you can pass it to a
method that accepts a parameter of dynamic type. Please note that Passing anonymous types
using dynamic is not recommended.
Ex: -

 Anonymous types are class type, directly derived from “System.Object” so they are reference type.
 If two or more Anonymous types have the same properties in same order in a same assembly
(same project) then compiler treats it as same type.
Ex: -
15. What are the collection types can be used in C#?
Simply, Collection is a set of objects of similar type, grouped together.

All the collections implement IEnumrable interface which is inherited from ICollection interface. We can
say that IEnumrable is the mother of all types of collections present in .NET.

 Standard Collection: This is found under system.Collections namespace.


 Generic Collection: This is found under system.Collections.Generic namespace. These are more
flexible to work with data
 Index based: Array, List
 Key value pair: Hashtable , Dictionary
 Prioritized Collection: Stack & Queues
 Specialized Collection: String Collection

Working with Array

int[] marks = new int[5] { 99, 98, 92, 97, 95};


int[] marks = new int[] { 99, 98, 92, 97, 95};
int[] marks = { 99, 98, 92, 97, 95};

//Arrays can store data of same Data Type


string[] arr=new string[2];
arr[0] = "welcome";
arr[1] = "Aspdotnet-suresh";

 Arrays are strongly typed entities. Arrays are collections of objects of the same type
 It’s a fixed size entity/type which means, if we define an array of size 10, then it will have the

space allocated for 10 elements and will need to loop through to find where the data is filled or
not.

 It’s a sequential collection which will be of the same type.


 Elements can be accessed by using the index of an element. Arrays are index based.

 Each index is initialized with a default value depending on the type of array created.

 Arrays can be used to store both Reference Types (Ex: - String) and Value Types (Ex: - int).

Working with ArrayList

 It is a sophisticated version of an array.


 It is one of the generic collection types present in System.Collection.Generic namespace.

 An ArrayList can be used to create a collection of any type, such as String, Int16 etc., and even
complex types.

 The object stored in the list can be accessed by an Index.


 Unlike arrays, List can grow its size automatically

 List has methods to search, sort, and manipulate the list.


 It uses both, the equality comparer as well as the ordering comparer.

 List class is a strongly typed class.

ArrayList al = new ArrayList();


al.Add(45);
al.Add(78);
al.Add(13);
al.Add(9); //Adding elements
al.Sort(); //Ascending Order
a1.Reverse(); // Reverses the order of the elements in the ArrayList

//ArrayList can store different datatype values


ArrayList strarr = new ArrayList();
strarr.Add("welcome"); // Add string values
strarr.Add(10); // Add integer values

strarr.Add(10.05); // Add float values

Difference between Array and ArrayList

 Arrays are used when the collection is of fixed length.


 Array is faster than ArrayList because array doesn't require boxing / un-boxing.
 Arrays are always strongly typed as compared to ArrayList.
 ArrayList can grow automatically.

Working with Hashtable

 It is a collection of Key-value pairs that are organized on the hash code of the key.
 It uses key to link the elements in the Collection.
 Key can be of any type.
 Key cannot be null.
 Value against a key can be null.
 It is not strongly typed.
 Strong type of Hashtable is called Dictionary.

Hashtable ht = new Hashtable();


ht.Add("001", "Zara Ali");
ht.Add("002", "Abida Rehman");
ht.Add("003", "Joe Holzner");
ht.Add("004", "Mausam Benazir Nur");

// Get a collection of the keys.


ICollection key = ht.Keys;
foreach (string k in key)
{
Console.WriteLine(k + ": " + ht[k]);
}

//Out Put:
001: Zara Ali
002: Abida Rehman
003: Joe Holzner
004: Mausam Benazir Nur

class HashTableProgram
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
foreach (DictionaryEntry de in ht)
{
int Key = (int)de.Key; //Casting
string value = de.Value.ToString(); //Casting
Console.WriteLine(Key + " " + value);
}

}
}

Difference between ArrayList and Hashtable


 Hashtable uses the key to access a specific element in a Collection whereas the ArrayList uses
index which is zero based.
 ArrayList is faster than Hashtable because there is no hashcoding involved in it.

Working with Dictionary


 A dictionary is used where fast lookups are critical.
 The Dictionary type provides fast lookups with keys to get values.
 With it we use keys and values of any type, including ints and strings.

public void MethodDictionary()


{
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("cat", 2);
dictionary.Add("dog", 1);
dictionary.Add("llama", 0);
dictionary.Add("iguana", -1);

//dictionary.Add(1, -2); // Compilation Error


foreach (KeyValuePair<string, int> pair in dictionary)
{
lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
}
}

 Hashtable is slower than the generic Dictionary type. Dictionary<TKey,TValue> is a


generic type

Differences between Hashtable and Dictionary

Dictionary:
 It returns error if we try to find a key which does not exist.
 It is faster than a Hashtable because there is no boxing and unboxing.
 Only public static members are thread safe.
 Dictionary is a generic type which means we can use it with any data type.
 While declaring itself we can specify the type of Key & Value, so no need to cast while
retrieving. Dictionary<string, int> dictionary = new Dictionary<string, int>();

Hashtable:
 It returns null if we try to find a key which does not exist.
 It is slower than dictionary because it requires boxing and unboxing.
 All the members in a Hashtable are thread safe,
 Hashtable is not a generic type,
 We can add any type of object to HashTable, but while retrieving we need to Cast it to the
required Type. So, it is not type safe

Working with Generic Collections

Generic separates the logic from the data type.

There are different variations of Collections, such as hash tables, queues, stacks, dictionaries, and ArrayList.
There are some sorted generic Collections, as well. The element of those can be accessed by using a key
as well as an index. But, for Generic Collection like Hashtable and Dictionaries, elements can be accessed
using a key only. Every Collection has a method to add, remove, and search an element function present
in the below namespace.

Working with Collection Interfaces : IEnumrable, ICollection, IList, IDictionary

These interfaces help us to achieve two big concepts of OOPS- Encapsulation and Polymorphism.

IEnumerator

 This helps to iterate over the Collection, without exposing the add, remove methods as in
ArrayList, and only helps in browsing the Collection.
 It has a method called GetEnumrator which returns IEnumerator object that helps to iterate over
Collection using foreach loop.
 Every .NET Collection implements IEnumerable interface.

ICollection
 This helps to iterate over the Collection, without exposing the add, remove methods as in
ArrayList, and also helps in browsing the Collection.
 It is inherited from IEnumrable Interface.
 It has extra count property which helps getting the count of elements in the Collection.

IList
 This helps to iterate over the Collection along with having the add & remove functionality.
 It helps to access the element using the index.
 It has the power of both, IEnumrable & ICollection interface.

IDictionary: This helps to iterate over the Collection with a key-value pair and also provides with add &
remove functionality.

Difference between IEnumrable & IQueryable


 IQueryable inherits from IEnumrable.
 IQueryable executes the query on server side with all filters whereas IEnumrable executes the
query and then filters the records.
 IQueryable is suitable for out-memory operations whereas IEnumrable is suitable for in-memory
operations, such as dataset, ArrayList.
 IQueryable does not support further filtering whereas IEnumrable supports further filtering of
data.
 IQueryable supports lazing loading and is best suitable for paging whereas IEnumrable doesn’t, as
it executes the query with all the filters.
 IQueryable supports custom query whereas IEnumrable doesn’t support custom query.
 IQueryable is derived from System.LINQ whereas IEnumrable derives from System.Collection.

16. What are collections and generics?

Collections:

 A collection is a container to which objects can be added.


 This container offers a powerful flexibility and adaptability.
 Collections often hold data items that are traversed in a loop structure.
 All of the items stored in the collection are stored as objects. This means that whatever type you
are putting in the collection is taken down to its root object form as it is put in the collection and
put back to its native form as it is pulled out.
 The act of taking a static instance of a particular class down to its base object type and back again
is referred to as boxing and unboxing.

Collections
String
Hash
Stacks
Array
Collections
Table Index based
Index based collections: Index based collections allow
Hybrid
Sorted
ArrayList
Queues
Dictionary
List us to find a value, based on by using internally created Key value pair
index.
Prioritized

Generics: Specialized

 Generics are introduced in C# 2.0. Generics allow us to design classes


and methods decoupled from the data types. That means, generics separates the logic from data
types.
 Generic classes are extensively used by collection classes available in System.Collections.Generic
namespace.
 With generics we can achieve Code reusability, type safe and performance.
 Generic Collections allow us to create flexible strong type collection.

Public class Calculator<T>{

Public static bool AreEqual<T>(T value1, T value2)

return value1.Equals(value2);

Class program {

Private static void Main(){

bool Equal = Calculator.AreEqual<int>(10,10);

17. Hash table Vs Dictionary

18. Arrays Vs Collections (OR) Array Vs ArrayList


19. ArrayList Vs Hashtable

20. How we can sort the array elements in descending order in C#?

21. Struct Vs Class (Value Type Vs Reference Type)

1. Structs are very similar to classes. We use struct keyword is used to create a struct and class

keyword is used to create a class.

2. Just like classes, struct can have fields, properties, constructors and methods.

3. Struct is a value type where as a class is a reference type.

4. All the differences that are applicable to value types and reference types are also applicable to

classes and structs.

5. Structs are stored on stack, where as classes are stored on heap.

6. Value types hold their value in memory where they are declared, but reference types hold a

reference to an object in memory.


7. Value types are destroyed immediately after the scope is lost. Where as reference types only

the reference variable is destroyed after the scope is lost. The object is later destroyed by

garbage collector.

8. When we copy a struct into another struct, a new copy of that struct gets created and

modifications on one struct will not affect the values contained by the other struct.

9. When we copy a class into another class, we only get a copy of the reference variable. Both

the reference variables point to the same object on the heap. So, operations on one variable

will affect the values contained by the other reference variable.

10. Structs cannot have destructors, but classes can have destructors.

11. Structs cannot have explicit parameter less constructors where as a class can have. Structs

Always Have Implicit Default Constructor.

12. Struct can’t inherit from another class where as a class can. Both structs and classes can

inherit from an interface.

13. Examples of struct in the .Net framework – int (System.Int32), double (System.Double) etc.

14. A class or struct cannot inherit from another struct. Structs are sealed types.

15. How do you prevent a class from being inherited? Or what is the significance of sealed

keyword.

22. Struct Vs Enum

23. Delegates & Events

24. Multicast delegates

25. Stack Memory Vs Heap Memory


26. Extension methods in C#

27. Boxing & Un boxing

Boxing
When a value type is converted to object type, it is called boxing.
Implicit conversion of a value type (int, char etc.) to a reference type (object), is known as Boxing. In
boxing process, a value type is being allocated on the heap rather than the stack.

Unboxing
When an object type is converted to a value type, it is called unboxing.
Explicit conversion of same reference type (which is being created by boxing process); back to a
value type is known as unboxing. In unboxing process, boxed value type is unboxed from the heap
and assigned to a value type which is being allocated on the stack.

Ex:
1. // int (value type) is created on the Stack
2. int stackVar = 12;
3.
4. // Boxing = int is created on the Heap (reference type)
5. object boxedVar = stackVar;
6.
7. // Unboxing = boxed int is unboxed from the heap and assigned to an int stack
variable
8. int unBoxed = (int)boxedVar;
28. Static Member

When a class member includes a static modifier, then the member is called as static member.
When no static modifier is present then the member is called as non static member or instance
member.

Static members are invoked using class name, where as instance members are invoked using
instances (objects) of the class.

An instance member belongs to specific instance (object) of a class. If I create 3 objects of a class, I
will have 3 sets of instance members in the memory, where as there will ever be only one copy of
a static member, no matter how many instances of a class are created.

Note: Class members = fields, methods, properties, events, indexers, constructors.


Ex:
Class Circle
{
Static float _PI;
Int _Radis;

//static constructor. It doesn’t allow any access modifiers.


Static Circle(){
Circle._PI = 3.141F;
}

//instance constructor
Public Circle(int Radius)
{
this._Radius = Radius;
}

Public float CalculateArea()


{

Return Circle._PI * this._Radius * this._Radius; //A=πr2

Class Program{
Public static void Main(){
Circle C1 = new Circle(5);
float Area1 = C1.CalculateArea();
Console.WriteLine(“Area = {0}”, Area1);

Circle C2 = new Circle(6);


float Area2 = C2.CalculateArea();
Console.WriteLine(“Area = {0}”, Area2);

}
}

29. Constructors (Different types of constructors)


Static Constructors: We use static constructors to initialize the static fields in a class. Static
constructor is called only once, no matter how many instances we create. Access modifiers are not
allowed on static constructors. Static Constructors are not accessible outside the class. Static
constructor will be called automatically when we refer a static member. Static constructors are
called before instance constructors and even before we refer static fields.

Instance Constructors: To initialize the instance fields we use instance constructors. Default access
modifier is Private. If it is private, then the constructor is accessible only inside of that class.
Outside the class we cannot access.

Constructor is a special method of a class which will invoke automatically whenever instance
or object of class is created. Constructors are responsible for object initialization and
memory allocation of its class. If we create any class without constructor, the compiler will
automatically create one default constructor for that class. There is always at least one
constructor in every class.

Here we need to remember that a class can have any number of constructors and
constructors don’t have any return type, not even void and within a class we can
create only one static constructor.

Generally, constructor name should be same as class name. If we want to create


constructor in a class, we need to create a constructor method name same as class name
check below sample method for constructor

class SampleA
{
public SampleA()
{
Console.WriteLine("Sample A Test Method");
}
}

Types of Constructors

Basically constructors are 5 types those are

1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor

Default Constructor
A constructor without having any parameters called default constructor. In this constructor
every instance of the class will be initialized without any parameter values like as shown
below

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample() // Default Constructor
{
param1 = "Welcome";
param2 = "Aspdotnet-Suresh";
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample(); // Once object of class created automatically constructor will be called
Console.WriteLine(obj.param1);
Console.WriteLine(obj.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output

Welcome
Aspdotnet-Suresh

Parameterized Constructors

A constructor with at least one parameter is called as parameterized constructor. In


parameterized constructor we can initialize each instance of the class to different values like
as shown below

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y) // Declaring Parameterized constructor with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample("Welcome","Aspdotnet-Suresh"); // Parameterized Constructor Called
Console.WriteLine(obj.param1 +" to "+ obj.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output

Welcome to Aspdotnet-Suresh

Constructor Overloading

In c# we can overload constructor by creating another constructor with same method name
and different parameters like as shown below

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;

public Sample() // Default Constructor


{
param1 = "Hi";
param2 = "I am Default Constructor";
}
public Sample(string x, string y) // Declaring Parameterized constructor with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample(); // Default Constructor will Called
Sample obj1=new Sample("Welcome","Aspdotnet-Suresh"); // Parameterized Constructor will Called
Console.WriteLine(obj.param1 + ", "+obj.param2);
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
When we run above program it will show output like as shown below
Output

Hi, I am Default Constructor


Welcome to Aspdotnet-Suresh

Copy Constructor

A parameterized constructor that contains a parameter of same class type is called as copy
constructor. Main purpose of copy constructor is to initialize new instance to the values of
an existing instance. It allows us to initialize a new object with the existing object
values. Check below example for this

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y)
{
param1 = x;
param2 = y;
}
public Sample(Sample obj) // Copy Constructor
{
param1 = obj.param1;
param2 = obj.param2;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample("Welcome", "Aspdotnet-Suresh"); // Create instance to class Sample
Sample obj1=new Sample(obj); // Here obj details will copied to obj1
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output

Welcome to Aspdotnet-Suresh
Static Constructor

When we declared constructor as static it will be invoked only once for any number of
instances of the class and it’s during the creation of first instance of the class or the first
reference to a static member in the class. Static constructor is used to initialize static fields
of the class and to write the code that needs to be executed only once.

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
static Sample()
{
Console.WriteLine("Static Constructor");
}
public Sample()
{
param1 = "Sample";
param2 = "Instance Constructor";
}
}
class Program
{
static void Main(string[] args)
{
// Here Both Static and instance constructors are invoked for first instance
Sample obj=new Sample();
Console.WriteLine(obj.param1 + " " + obj.param2);
// Here only instance constructor will be invoked
Sample obj1 = new Sample();
Console.WriteLine(obj1.param1 +" " + obj1.param2);
Console.ReadLine();
}
}
}
When we run above program we will get output like as shown below

Output

Static Constructor
Sample Instance Constructor
Sample Instance Constructor
Importance points of static constructor

- Static constructor will not accept any parameters because it is automatically called
by CLR.
- Static constructor will not have any access modifiers.
- Static constructor will execute automatically whenever we create first instance of
class
- Only one static constructor will have allowed.

Private Constructor

Private constructor is a special instance constructor used in a class that contains static
member only. If a class has one or more private constructor and no public constructor, then
other classes are not allowed to create instance of this class this mean we can neither
create the object of the class nor it can be inheriting by other class. The main purpose of
creating private constructor is used to restrict the class from being instantiated when it
contains every member as static.

using System;
namespace ConsoleApplication3
{
public class Sample
{
public string param1, param2;
public Sample(string a,string b)
{
param1 = a;
param2 = b;
}
private Sample() // Private Constructor Declaration
{
Console.WriteLine("Private Constructor with no prameters");
}
}
class Program
{
static void Main(string[] args)
{
// Here we don't have chance to create instace for private constructor
Sample obj = new Sample("Welcome","to Aspdotnet-Suresh");
Console.WriteLine(obj.param1 +" " + obj.param2);
Console.ReadLine();
}
}
}

Output

Welcome to Aspdotnet-Suresh

In above method we can create object of class with parameters will work fine. If create
object of class without parameters it will not allow us to create.

// it will works fine


Sample obj = new Sample("Welcome","to Aspdotnet-Suresh");
// it will not work because of inaccessability
Sample obj=new Sample();
Important points of private constructor

- One use of private constructor is when we have only static member.


- Once we provide a constructor that is either private or public or any, the compiler will not
allow us to add public constructor without parameters to the class.
- If we want to create an object of class even if we have private constructor then we need to
have public constructor along with private constructor

30. Constructors Vs Destructors


31. What is the use of c# “Yield” keyword
32. iEnumerable vs iEnumerator
33. LINQ
34. Out, Ref, Param
35. optional parameters in c#
36. Async and Await
37. Exception handling
38. Garbage collector and generation of garbage collector
39. Dispose Vs Finalize
40. Thread & States of a Thread
Threading: Threading helps us to execute program code parallely.

Background threads die off if main app exits.

Foreground threads exists/stays even if main app exists.

ADO.Net

1. What is DataReader Object?

Datareader is an object of ADO.Net which provides access to data from a specified data source. It
consists of classes which sequentially read data from a data source like Oracle, SQL or Access .

2. What is Dataset Object?

A Dataset is set to be collection of data with a tabular column representation. Each column in the
table represents a variable and the row represents to value of a variable. This Dataset object can
be obtained from the database values.

3. What is object pooling?


Object pooling is nothing but a repository of the objects in memory which can be used later. This
object pooling reduces the load of object creation when it is needed. Whenever there is a need of
object, object pool manager will take the request and serve accordingly.

4. What is connection pooling?

Connection pooling consists of database connection so that the connection can be used or reused
whenever there is request to the database. This pooling technique enhances the performance of
executing the database commands. This pooling definitely reduces our time and effort.

5. What is Data view?

Data view is the representation of data in various formats and it can be requested by the users.
Data can be exposed in different sort orders or filter on the user condition with the help of Data
view. Data Customization is also possible through Data View.

6. What is Data Adapter?

Data Adapter is a part of ADO.NET data provider which acts as a communicator between Dataset
and the Data source. This Data adapter can perform Select, Insert, Update and Delete operations
in the requested data source.

7. What is the use of SqlCommand object?


SQLCommand object that allows user to interact with the database. This object mainly used to
query the database and it can be of different types – Select, Insert, Modify and Delete .

8. What is the difference between Datareader and Dataset?

Following table gives difference between DataReader and Dataset:

DataReader Dataset

Forward only Loop through Dataset

Connected Recordset Disconnected Recordset

Single table involved Multiple tables involved

No relationship required Relationship between tables maintained

No XML storage Can be stored as XML

Occupies Less Memory Occupies More memory

Read only Can do addition / Updation and Deletion

Features of ADO.Net:

 Data Paging
 Bulk Copy Operation
 New Data Controls
 Datareader’s execute methods.

Components of ADO.Net data provider

 Connection object – Represents connection to the Database


 Command object – Used to execute stored procedure and command on
Database
 ExecuteNonQuery – Executes command but doesn’t return any value
 ExecuteScalar – Executes and returns single value
 ExecuteReader – Executes and returns result set
 DataReader – Forward and read only recordset
 DataAdapter – This acts as a bridge between database and a dataset.
Execute methods of Ado.Net?

Following are different execute methods of ADO.Net command object:

 ExecuteScalar – Returns single value from the dataset


 ExecutenonQuery – Returns resultset from dataset and it has multiple
values
 ExecuteReader – Forwardonly resultset
 ExecuteXMLReader – Build XMLReader object from a SQL Query

SQL Questions

9. What Is nth highest salary of the employee


nd
2 highest salary using sub-query

Select top 1 salary from


(select distinct top 2 salary from Employees order by salary order by salary desc)
Result Order by Salary

Using CTE (Common table expression)

With Result as
(
Select salary, Dense_Rank() over (order by salary desc) AS DenseRank from Employees
)
Select top 1 salary from Result Where Result.DenseRank = 2
Scope of temp table & temp variable

Temporary Table:

Syntax: CREATE TABLE #T(…)

Ex: CREATE TABLE #Temp (col1 int, col2 int)

A Temporary Table or Temp-Table is created on disk in the tempDB system database . The name of this
Temp-Table is suffixed with a session-specific ID so that I can be differentiated with other similar named
tables created in other sessions. The name is limited to 116 chars.

The Scope of this Temp-Table is limited to its session, like a Stored Procedure, or a set of nested Stored
Procedures.

The Temp-Table gets Dropped automatically when the session ends or the stored Procedure execution
ends or goes out of scope.

One of the main benefits of using a #temp table, as opposed to a permanent table, is the reduction in
the amount of locking required(since the current user is the only user accessing the table), and also
there is much less logging involved.

Global Temporary Tables (##) operate much like local temporary tables. They are also created in tempdb
and cause less locking and logging than permanent tables. However, they are visible to all the sessions,
until the session goes off.

Indexes

Cursors

Views Manipulations(i.e update,..)

Common table expressions (CTE)

Partition , Rank & Dense_Rank in SQL

Group by & Having

Joins

Where trigger holds the data

Why we can’t create more than one cluster index for a table.

How to debug SQL.

ASP.Net MVC

How data flows from client to server’s action control method.

Anti forgery token [Cross site scripting]


ChildActionOnly

Authorize & AllowAnonymous Action Filters

How to overcome SQL Injections

Data Annotations

How server identifies the session object of each client

How to enable View State

Action Filters in real time

View State

State Management Techniques

How to update Partial views

Html Helpers

MVC http request life cycle

Application Life cycle

Http Handlers

Http Modules

Attributed Routing [Can we call same controller action method with different URLs?]

You might also like