Interview QSNS (Repaired)
Interview QSNS (Repaired)
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.
Interface members are public by default, and they don’t allow explicit access modifiers.
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 ICustomer1
{
void Print1();
}
2. Abstract Class
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 class ContractEmployee : BaseEmployee{
Public int HourlyPay {get; set;}
Public int TotalPay {get; set;}
Public override int GetMonthlySalary(){
Return this.TotalHours*this.HourlyPay;
}
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
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.
Ex:
public class Employee
{
public virtual void DoWork()
{
//Do work
}
}
public class JuniorDeveloper:Manager, Developer// Compile Time Error :Cannot have multiple
base classes but assume that it were possible
{
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
}
}
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.
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
Polymorphism:
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 Program
{
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 −
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.
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
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:
return con;
SingletonDBclass. GetConnection();
When working on large projects, spreading a class over separate files enables multiple programmers
to work on it at the same time.
File1.cs
File2.cs
public partial class Employee
{
public void GoToLunch()
{
}
}
There are some points that you should be when you are developing a partial class in your application.
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.
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.
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.
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();
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.
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:
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.
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.
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).
An ArrayList can be used to create a collection of any type, such as String, Int16 etc., and even
complex types.
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.
//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);
}
}
}
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
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.
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.
Collections:
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
return value1.Equals(value2);
Class program {
20. How we can sort the array elements in descending order in C#?
1. Structs are very similar to classes. We use struct keyword is used to create a struct and class
2. Just like classes, struct can have fields, properties, constructors and methods.
4. All the differences that are applicable to value types and reference types are also applicable to
6. Value types hold their value in memory where they are declared, but reference types hold a
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
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
12. Struct can’t inherit from another class where as a class can. Both structs and classes can
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.
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.
//instance constructor
Public Circle(int Radius)
{
this._Radius = Radius;
}
Class Program{
Public static void Main(){
Circle C1 = new Circle(5);
float Area1 = C1.CalculateArea();
Console.WriteLine(“Area = {0}”, Area1);
}
}
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.
class SampleA
{
public SampleA()
{
Console.WriteLine("Sample A Test Method");
}
}
Types of Constructors
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
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;
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.
ADO.Net
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 .
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.
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.
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.
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.
DataReader Dataset
Features of ADO.Net:
Data Paging
Bulk Copy Operation
New Data Controls
Datareader’s execute methods.
SQL Questions
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:
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
Joins
Why we can’t create more than one cluster index for a table.
ASP.Net MVC
Data Annotations
View State
Html Helpers
Http Handlers
Http Modules
Attributed Routing [Can we call same controller action method with different URLs?]