Thursday, 8 October 2015

Basic Questions


What is object-oriented programming (OOP)?
OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object is created in the program to represent a class. Therefore, an object encapsulates all the features, such as data and behavior that are associated to a class. OOP allows developers to develop modular programs and assemble them as software. Objects are used to access data and behaviors of different software modules, such as classes, namespaces, and sharable assemblies.

What is C#?
C# is an object oriented, type safe and managed language that is compiled by .Net framework to generate Microsoft Intermediate Language.

Why to use “using” in C#?
“Using” statement calls – “dispose” method internally, whenever any exception occurred in any method call and in “Using” statement objects are read only and cannot be reassignable or modifiable.

 ---------------------------------- namespace ---------------------------------- 
 Explain namespaces in C#?
Namespaces are containers for the classes. We will use namespaces for grouping the related classes in C#. “Using” keyword can be used for using the namespace in other namespace.

Mention the assembly name where System namespace lies in C#?
Assembly Name – mscorlib.dll

 ---------------------------------- Class ---------------------------------- 
 Explain sealed class in C#?
Sealed class is used to prevent the class from being inherited from other classes. So “sealed” modifier also can be used with methods to avoid the methods to override in the child classes.

 ---------------------------------- Object ----------------------------------
What is an object?  
An object is an instance of a class through which we access the methods of that class. “New” keyword is used to create an object. A class that creates an object in memory will contain the information about the methods, variables and behavior of that class. 

Explain object pool in C#?
Object pool is used to track the objects which are being used in the code. So object pool reduces the object creation overhead.
 
 ---------------------------------- Array ---------------------------------- 
What is an Array?
An array is a collection of related instance either value or reference types. Array posses an immutable structure in which the number of dimensions and size of the array are fixed at instantiation.

C# Supports Single, Mult dimensional and Jagged Array.

Single Dimensional Array: it is sometimes called vector array consists of single row.

Multi-Dimensional Array: are rectangular & consists of rows and columns.

Jagged Array: also consists of rows & columns but in irregular shaped (like row 1 has 3 column and row 2 has 5 column). The array which has elements of type array is called jagged array. The elements can be of different dimensions and sizes. We can also call jagged array as Array of arrays.

What is an ArrayList?
ArrayList is a dynamic array. Elements can be added & removed from an arraylist at the runtime.
An arraylist is similar to an array but it doesn’t have a fixed size.


What is BitArray?
The BitArray collection is a composite of bit values. It stores 1 or 0 where 1 is true and 0 is false. This collection provides an efficient means of storing and retrieving bit values.

  ---------------------------------- Hashtable ----------------------------------
Explain Hashtable in C#?
It is used to store the key/value pairs based on hash code of the key. Key will be used to access the element in the collection. For example,
Hashtable myHashtbl = new Hashtable();
myHashtbl.Add("1", "TestValue1");
myHashtbl.Add("2", "TestValue2");

  ---------------------------------- Try, Catch, Finally ----------------------------------
Why to use “finally” block in C#?
“Finally” block will be executed irrespective of exception. So while executing the code in try block when exception is occurred, control is returned to catch block and at last “finally” block will be executed. So closing connection to database / releasing the file handlers can be kept in “finally” block.

Can we have only “try” block without “catch” block in C#?
Yes we can have only try block without catch block.
  
Can multiple catch blocks be executed?
No, Multiple catch blocks can’t be executed. Once the proper catch code executed, the control is transferred to the finally block and then the code that follows the finally block gets executed.

Do we get error while executing “finally” block in C#?
Yes. We may get error in finally block.

What is the difference between “throw ex” and “throw” methods in C#?
  • “throw ex” will replace the stack trace of the exception with stack trace info of re throw point.
  • “throw” will preserve the original stack trace info

In try block if we add return statement whether finally block is executed in C#?
Yes. Finally block will still be executed in presence of return statement in try block.

 ---------------------------------- static, public, void, protected, private ----------------------------------
What are the differences between static, public and void in C#?
  • Static classes/methods/variables are accessible throughout the application without creating instance. Compiler will store the method address as an entry point. 
  • Public methods or variables are accessible throughout the application. 
  • Void is used for the methods to indicate it will not return any value.

Explain “static” keyword in C#?
“Static” keyword can be used for declaring a static member. If the class is made static then all the members of the class are also made static. If the variable is made static then it will have a single instance and the value change is updated in this instance.

Explain access modifier – “protected internal” in C#?
“protected internal” can be accessed in the same assembly and the child classes can also access these methods.
 
Can we use “this” inside a static method in C#?
No. We can’t use “this” in static method.

Can a private virtual method be overridden?  
No, because they are not accessible outside the class.

 ---------------------------------- delegate ----------------------------------   
What you mean by delegate in C#?
Delegates in c# are type safe objects, which are used to hold reference of one or more methods. Delegate is used to represent the reference of the methods of same return type and parameters.

Whenever we want to create delegate methods we need to declare with delegate keyword and delegate methods signature should match exactly with the methods which we are going to hold like same return types and same parameters otherwise delegate functionality won’t work if signature not match with methods.

Single Cast Delegates
public delegate int DelegatSample(int a,int b);
public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x - y;
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
DelegatSample delgate1 = sc.Add;
int i = delgate1(10, 20);
Console.WriteLine(i);
DelegatSample delgate2 = sc.Sub;
int j = delgate2(20, 10);
Console.WriteLine(j);
}
}
Output:

Add Result : 30
Sub Result : 10

Multi Cast Delegates:
Multi cast delegate is used to hold address of multiple methods in single delegate. To hold multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -=
Multicast delegates will work only for the methods which have return type only void. If we want to create a multicast delegate with return type we will get the return type of last method in the invocation list 
public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}
Output:
Addition Value : 15
Subtraction Value : 5
Multiply Value : 50

What is the use of Delegates?
Suppose if you have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates.

What are the types of delegates in C#?
Below are the uses of delegates in C# -
  • Single Delegate
  • Multicast Delegate
  • Generic Delegate

What are the three types of Generic delegates in C#?

Below are the three types of generic delegates in C# -
  • Func
  • Action
  • Predicate

---------------------------------- Variable Types ---------------------------------- 
The variables in C#, are categorized into the following types:
  • Value types
  • Reference types
  • Pointer types

Value Type:Value type variables can be assigned a value directly. They are derived from the class System.ValueType.
When you declare an int type, the system allocates memory to store the value.
Examples are bool, byte, int, char, decimal, double, long, sbyte, short, uint, ulong, ushort and float, which stores numbers, alphabets, and floating point numbers, respectively.

Reference Type:
 The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables.
Example of built-in reference types are: object, dynamic, and string.
User-defined reference types are: class, interface, or delegate.

Object Type:
The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion.

Dynamic Type:
You 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:
dynamic <variable_name> = value;
For example,
dynamic d = 20;

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.

Pointer Type:
Pointer type variables store the memory address of another type.
Syntax:
type* identifier;
For example:
char* cptr;
int* iptr;

---------------------------------- boxing, unboxing ----------------------------------
When a value type is converted to object type, it is called boxing 
when an object type is converted to a value type, it is called unboxing.
object obj;
obj = 100; // this is boxing


---------------------------------- Type conversion /  Type Casting ----------------------------------
 Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#, type casting has two forms:
  • Implicit type conversion - These conversions are performed by C# in a type-safe manner. For example, conversions from smaller to larger integral types and conversions from derived classes to base classes.
  • Explicit type conversion - These conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator.

 ---------------------------------- Other ----------------------------------  
Explain the types of comments in C#?
Below are the types of comments in C# -
  • Single Line Comment Eg : //
  • Multiline Comments Eg: /* */
  • XML Comments Eg : /// 

What are value types in C#?
Below are the list of value types in C# -
  • decimal
  • int
  • byte
  • enum
  • double
  • long
  • float


What are reference types in C#?
Below are the list of reference types in C# -
  • class
  • string
  • interface
  • object

What is the difference between “constant” and “readonly” variables in C#?
  • “Const” keyword is used for making an entity constant. We cannot modify the value later in the code. Value assigning is mandatory to constant variables.   
    Eg: const string _name = "Test";
  • “readonly” variable value can be changed during runtime and value to readonly variables can be assigned in the constructor or at the time of declaration.
 
What is the difference between “dispose” and “finalize” variables in C#?
  • Dispose - This method uses interface – “IDisposable” interface and it will free up both managed and unmanaged codes like – database connection, files etc.
  • Finalize - This method is called internally unlike Dispose method which is called explicitly. It is called by garbage collector and can’t be called from the code.

What are circular references?
Circular reference is situation in which two or more resources are interdependent on each other causes the lock condition and make the resources unusable.

What is lock statement in C#?
Lock ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread attempts to enter a locked code, it will wait, block, until the object is released.

 Difference between Structure and class :-

  • Structure is stored within stack memory and Class is stored within heap memory.
  • In Structure we can not define parameter less constructor but in class can do it.
  • In structure we can not initialize the data member at declaration but in class can do it. 
  • In structure inheritance is not possible(one structure can not inherited to another structure )but in class it is possible.
  • We can not declare virtual override and abstract keyword with structure but in class it is possible.
  • Class is Reference type but structure is value type.
  • We can use Destructor in Class but not in Structure.
More Details Refer: http://www.msdotnet.co.in/2013/04/structure-and-class-in-c.html



Tuesday, 6 October 2015

All file extensions in .NET

.aspx : page in WebForms. Contains controls and events

.asax : Global.asax, used for application-level logic

.ascx : Web UserControls: custom controls to be placed onto web pages.

.ashx : custom HTTP handlers. Generic handler. Can be used in various ways* as generate pages, sharing information, display pictures

.asmx : web service pages. Modality of sharing information from/to website. From version 2.0 a Code behind page of an asmx file is placed into the app_code folder.

.axd : when enabled in web.config requesting trace.axd outputs application-level tracing. Also used for the special webresource.axd handler which allows control/component developers to package a component/control complete with images, script, css etc. for deployment in a single file (an 'assembly')

.config : web.config is the only file in a specific Web application to use this extension by default (machine.config similarly affects the entire Web server and all applications on it), however ASP.NET provides facilities to create and consume other config files. These are stored in XML format.

.cs/vb : Code files (cs indicates C#, vb indicates Visual Basic). Code behind files (see above) predominantly have the extension ".aspx.cs" or ".aspx.vb" for the two most common languages. Other code files (often containing common "library" classes) can also exist in the web folders with the cs/vb extension. In ASP.NET 2 these should be placed inside the App_Code folder where they are dynamically compiled and available to the whole application.

.dbml : LINQ to SQL data classes file

.master : 2.0 master page file

.resx : resource files for internationalization and localization. Resource files can be global (e.g. messages) or "local" which means specific for a single aspx or ascx file.

.sitemap : sitemap configuration files. Default file name is web.sitemap

.skin : theme skin files.

.svc : Windows Communication Foundation service file

browser : browser capabilities files stored in XML format; introduced in version 2.0. ASP.NET 2 includes many of these by default, to support common web browsers. These specify which browsers have which capabilities, so that ASP.NET 2 can automatically customize and optimize its output accordingly. Special .browser files are available for free download to handle, for instance, the W3C Validator, so that it properly shows standards-compliant pages as being standards-compliant. Replaces the harder-to-use BrowserCaps section that was in machine.config and could be overridden in web.config in ASP.NET 1.x.

Friday, 20 February 2015

Differences between using a SQL Server Compact database (.sdf) and SQL Server database

SQL Server Compact database (.sdf):
  • max 2 GB file size
  • No stored procedures, triggers etc.
  • No process but loaded into your AppDomain
  • As far as I know, there is no cost based optimizer or query plans for queries
  • Lack of concurrent access of multiple users at the same time
The big issue here is, that CE is only a file on your system and you get access through a simple InApp-call using a dll. Thats it and in many scenarios this is enough.

Remember, that you need to deploy the CE-DLL when you wan't to publish your app!
SQL Server Compact doesn't have any in-memory cache, so all queries hit disk all the time. 
SQL Compact doesn't support Stored Procedures. You write all of your query directly in code.

SQL Server database:
With SQL Server Express hot data stays in memory which can speed queries up significantly, especially if the queries are run often

Useful Compare Link:

  1. Comparison of SQL Server Compact, SQLite, SQL Server Express and LocalDB
  2. Differences Between SQL Server Compact and SQL Server
  3. SQL SERVER – Difference Between SQL Server Compact Edition (CE) and SQL Server Express Edition

Thursday, 19 February 2015

[ADO.NET] Difference Between DataReader, DataSet, DataAdapter and DataTable in C#

DataReader
DataReader is used to read the data from database and it is a read and forward only connection oriented architecture during fetch the data from database. DataReader will fetch the data very fast when compared with dataset. Generally we will use ExecuteReader object to bind data to datareader.
To bind DataReader data to GridView we need to write the code like as shown below:
 
Protected void BindGridview()
{
using (SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
SqlDataReader sdr = cmd.ExecuteReader();
gvUserInfo.DataSource = sdr;
gvUserInfo.DataBind();
conn.Close();
}
}
  • Holds the connection open until you are finished (don't forget to close it!).
  • Can typically only be iterated over once
  • Is not as useful for updating back to the database
DataSet
DataSet is a disconnected orient architecture that means there is no need of active connections during work with datasets and it is a collection of DataTables and relations between tables. It is used to hold multiple tables with data. You can select data form tables, create views based on table and ask child rows over relations. Also DataSet provides you with rich features like saving data as XML and loading XML data.
protected void BindGridview()
{
    SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
    conn.Open();
    SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    gvUserInfo.DataSource = ds;
    gvUserInfo.DataBind();
}
DataAdapter
DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is used to read the data from database and bind that data to dataset. Dataadapter is a disconnected oriented architecture. Check below sample code to see how to use DataAdapter in code:
protected void BindGridview()
{
    SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
    conn.Open();
    SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    gvUserInfo.DataSource = ds;
    gvUserInfo.DataBind();
}
  • Lets you close the connection as soon it's done loading data, and may even close it for you automatically
  • All of the results are available in memory
  • You can iterate over it as many times as you need, or even look up a specific record by index
  • Has some built-in faculties for updating back to the database.
DataTable

DataTable represents a single table in the database. It has rows and columns. There is no much difference between dataset and datatable, dataset is simply the collection of datatables.

protected void BindGridview()
{
     SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
     conn.Open();
     SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
     SqlDataAdapter sda = new SqlDataAdapter(cmd);
     DataTable dt = new DataTable();
     da.Fill(dt);
     gridview1.DataSource = dt;
     gvidview1.DataBind();
}