Type Conversion & Type Casting


Type Conversion

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, are 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.



 C# Type Conversion Methods : 


Sr.No.Methods & Description
1
ToBoolean
Converts a type to a Boolean value, where possible.
2
ToByte
Converts a type to a byte.
3
ToChar
Converts a type to a single Unicode character, where possible.
4
ToDateTime
Converts a type (integer or string type) to date-time structures.
5
ToDecimal
Converts a floating point or integer type to a decimal type.
6
ToDouble
Converts a type to a double type.
7
ToInt16
Converts a type to a 16-bit integer.
8
ToInt32
Converts a type to a 32-bit integer.
9
ToInt64
Converts a type to a 64-bit integer.
10
ToSbyte
Converts a type to a signed byte type.
11
ToSingle
Converts a type to a small floating point number.
12
ToString
Converts a type to a string.
13
ToType
Converts a type to a specified type.
14
ToUInt16
Converts a type to an unsigned int type.
15
ToUInt32
Converts a type to an unsigned long type.
16
ToUInt64
Converts a type to an unsigned big integer.




Type Casting

The meaning of Type Casting is to change one data type into another data type. Developers change data type according to their need.

Types of casting in C#
1. Implicit Conversion
2. Explicit Conversion


Implicit Conversion
Implicit Conversion is done by the compiler itself.

private void ImplicitClick_Click(object sender, EventArgs e)  
{  
    int firstValue = 25;  
    int secondValue = 26;  
    long result = firstValue + secondValue;  
    //MessageBox.Show(result.ToString());         


Explicit Conversion
Explicit Conversion is done by the users according to their need/requirement. We tell the compiler to do the conversion. 
private void btnCast_Click(object sender, EventArgs e)  
{  
    int firstName = int.Parse(txtFirstNumber.Text);  
    int secondName = int.Parse(txtSecondNumber.Text);
    MessageBox.Show((firstName + secondName).ToString());  
}  

Difference between Dispose & Finalize Method

COMPARISON BASISDISPOSE( )FINALIZE( )
DefinedThe method dispose( ) is defined in the interface IDisposable interface.The method finalize( ) id defined in java.lang.object class.
Syntaxpublic void Dispose( ){
// Dispose code here
}
protected void finalize( ){
// finalization code here
}
InvokedThe method dispose( ) is invoked by the user.The method finalize( ) is invoked by the garbage collector.
PurposeMethod dispose( ) is used to free unmanaged resources whenever it is invoked.Method finalize( ) is used to free unmanaged resources before the object is destroyed.
ImplementationThe method dispose( ) is to be implemented whenever there is a close( ) method.The method finalize( ) is to be implemented for unmanaged resources.
Access specifierThe method dispose( ) is declared as public.The method finalize( ) is declared as private.
ActionThe method dispose( ) is faster and instantly disposes an object.The method finalize is slower as compared to dispose
PerformanceThe method disposes( ) performs the instantaneous action hence, does not effect the performance of websites.The method finalize( ) being slower affects the performance of the websites.

Threading in C#

Threading enables C# program to perform concurrent processing so that you can do more than one operation at a time. 

In order to create threading in C#, we need to import threading namespace i.e. System.Threading. Using this namespace we can create thread object which can help us to create thread applications.

For creating threading application, there some important methods which used regularly for implementing threading.
1 : Thread Join
2 : Thread Sleep
3 : Thread Abort

Thread Join
Thread.Join() make thread to finish its work or makes other thread to halt until it finishes work. Join method when attached to any thread, it makes that thread to execute first and halts other threads.

Thread Sleep
Thread.Sleep a method used to suspend current thread for a specific interval of time. Time can be specified in milliseconds or Timespan.

Thread Abort
As name implies "Abort" so same way Thread.Abort helps to end or abort any thread to process it further. It raises ThreadAbortException in the thread for process of termination.


Types of Threads in C#
There are two types of Thread in Csharp i.e. Foreground Thread and Background Thread.
1)  Foreground threads are those threads which keeps running until it finishes his work even if the Main method thread quits its process. Lifespan of foreground threads does not depends on main thread.
2)  Background thread is just opposite of foreground thread here background thread quits its job when main thread quits. Lifespan of background threads depends on main thread. In order to implement background thread in a program we need to set property called IsBackground to true.

Difference Between Dictionary And Hashtable In C#

Dictionary and Hashtable are both used to hold the data as key-value pairs in C#.

Dictionary
Dictionary is generic type Dictionary
Dictionary class is a strong type < TKey,TValue > Hence, you must specify the data types for key and value.
There is no need of boxing/unboxing.
When you try to access non existing key dictionary, it gives runtime error.
Dictionary maintains an order of the stored values.
There is no need of boxing/unboxing, so it is faster than Hashtable.

Hashtable
Hashtable is non-generic type.
Hashtable is a weakly typed data structure, so you can add keys and values of any object type.
Hashtable needs boxing/unboxing, so it is slower than Dictionary.
When you try to access non existing key Hashtable, it gives null values.
Hashtable never maintains an order of the stored values.

WCF - Windows Communication Foundation

Windows Communication Foundation - It takes many existing communication technologies, such as Web Services, Windows Remoting, Microsoft Message Queuing, and abstracts them into a single technology.  In most cases, this simplifies the way you communicate with other applications.  It also allows you to communicate with other applications without being coupled to a specific technology.  Therefore, you could use Web Services over SOAP to begin with, and later move to remote procedure calls (RPC) without changing your code, just the configuration of WCF.


WCF defines four types of contracts :

1. Service contracts :  Describe which operations the client can perform on the service.  
2. Data contracts :  Define which data types are passed to and from the service. WCF defines
    implicit     contracts for built-in types such as int and string, but we can easily define explicit opt-
    in data contracts for custom types. 
3. Fault contracts :  Define which errors are raised by the service, and how the service handles and   
    propagates errors to its clients. 
4. Message contracts  :  Allow the service to interact directly with messages.
    Message contracts can be  typed  or untyped, and are useful in interoperability cases and when
    there    is an existing message format we have to comply with.
5Operation ContractAn operation contract is defined within a service contract. It defines the
    parameters and return type of an operation. An operation contract can also defines operation-level
    settings, like as the transaction flow of the operation, the directions of the operation (one-way,
    two-way, or both ways), and fault contract of the operation.


SQL - Transactions


Sometimes we come across a situation where we  need to execute two or more SQL commands in such a way that - if any one of the statements fails, then no other statement will be able to change the database. For that we can use concept TRANSACTION
There are three importance commands to manage a transaction. BEGIN TRANSACTION will begin a transaction, COMMIT TRANSACTION will commit the transaction to the database, and ROLLBACK TRANSACTION will roll the transaction back.
Within .NET, transactions are managed with the System.Data.SqlClient.SqlTransaction class.A transaction exists over a SqlConnection object  and thus all the SqlCommand objects you create using that connection. Let's look at a quick example:

using System.Data.SqlClient;
SqlConnection myConnection = new SqlConnection("");
        myConnection.Open();

// Start a local transaction
SqlTransaction myTrans = myConnection.BeginTransaction();

SqlCommand myCommand = new SqlCommand();
myCommand.Connection = myConnection;
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText = "Insert into user_reg (your column name)VALUES (your values goes here)";
myCommand.ExecuteNonQuery();
myCommand.CommandText = "delete from user_reg where ID=101";//
// Attempt to commit the transaction.
myCommand.ExecuteNonQuery();
myTrans.Commit();
Response.Write("Both records are written to database.");
}
catch (Exception ep)
{
// Attempt to roll back the transaction.
myTrans.Rollback();
Response.Write(ep.ToString());
Response.Write("Neither record was written to database.");
}
finally
{
myConnection.Close();
}

As you can see from this example, we first open a connection to the SQL database. We then call the BeginTransaction method on the connection, keeping a reference to the object that it returns. At this point, the connection is bound to the SqlTransaction object that was returned. This means that any SqlCommand executed on that connection will be within the transaction.
There are essentially, two operations you can use on the SqlTransaction object. Rollback will cancel your transaction, undoing all the changes that have been made. Commit will cause the transaction to be written to the database permanently. Either case will end the transaction.
Transactions are useful for several other things. First, they provide a way to rollback a group of SQL statements if a single one should.


Properties of Transactions

Transactions have the following four standard properties, usually referred to by the acronym ACID.

Atomicity − ensures that all operations within the work unit are completed successfully. Otherwise, the transaction is aborted at the point of failure and all the previous operations are rolled back to their former state.

Consistency − ensures that the database properly changes states upon a successfully committed transaction.

Isolation − enables transactions to operate independently of and transparent to each other.

Durability − ensures that the result or effect of a committed transaction persists in case of a system failure.


Transaction Control

The following commands are used to control transactions.

COMMIT − to save the changes.

ROLLBACK − to roll back the changes.

SAVEPOINT − creates points within the groups of transactions in which to ROLLBACK.

SET TRANSACTION − Places a name on a transaction.

Difference between a primary and unique key

Primary Keys
The main purpose of the primary key is to provide a means to identify each record in the table.


A primary key has the following characteristics:
There can only be one primary key for a table.
The primary key consists of one or more columns.
The primary key enforces the entity integrity of the table.
All columns defined must be defined as NOT NULL.
The primary key uniquely identifies a row.
Primary keys result in CLUSTERED unique indexes by default.


---------------------


Unique Keys
A unique key can be used to ensure rows are unique within the database.

Consider the Employee table below:
Table with primary and unique key
Assuming that EmployeeID is the primary key, then we may want to place a unique constraint on Government-Number to ensure each employee has their own number.

In SQL Server the unique key has the following characteristics:
There can be multiple unique keys defined on a table.
Unique Keys result in NONCLUSTERED Unique Indexes by default.
One or more columns make up a unique key.
Column may be NULL, but on one NULL per column is allowed.
A unique constraint can be referenced by a Foreign Key Constraint.



Primary and Unique Key Comparison
primary and unique key comparison

Difference Between ViewData, ViewBag and TempData in MVC

ViewData is used to pass data from controller to view.
It is derived from ViewDataDictionary class.
It is available for the current request only.
Requires typecasting for complex data type and checks for null values to avoid error.
If redirection occurs, then its value becomes null.

In this example, a string value is set in the ViewData object in Controller and it is then displayed in View.
Controller
public class FirstController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Hello MVC!";
        return View();
    }
}

View
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <div>
        @ViewData["Message"]
    </div>
</body>
</html>

--------------------------------------

ViewBag is also used to pass data from the controller to the respective view.
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
It is also available for the current request only.
If redirection occurs, then its value becomes null.
Doesn’t require typecasting for complex data type.

In this example, a string value is set in the ViewBag object in Controller and it is then displayed in View.
Controller
public class FirstController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Hello MVC!";
        return View();
    }
}

View
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <div>
        @ViewBag.Message
    </div>
</body>
</html>

--------------------------------------

TempData is derived from TempDataDictionary class.
TempData is used to pass data from the current request to the next request.
It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action.
It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages.

In this example, a string value is set in the TempData object in Controller and it is redirected to another Controller and finally it is displayed in View.
First Controller
public class FirstController : Controller
{
    public ActionResult Index()
    {
        TempData["Message"] = "Hello MVC!";
        return new RedirectResult(@"~\Second\");
    }
}

Second Controller
public class SecondController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

View of Second Controller
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <div>
        @TempData["Message"];
    </div>
</body>
</html>

Difference Between Boxing and Unboxing in C#

Boxing is a procedure of converting a value type to an object type. Here, the value type is stored on the stack and the object type is stored in the heap memory.

Let’s understand Boxing with an example :
int i = 24;
object ob = i; // Box the integer type n into object type ob.

In above code, the integer type i containing value 24 is stored on the stack and is copied to the object type ob. An object type is now referring to an integer value.  Now the “int i” also contain value 24 and the “object type ob” also contain value 24, but both the values are independent of each other i.e. if you change the value of i, it won’t reflect the change in the value of ob.



Unboxing is a conversion of the object type to the value type. In Unboxing the value of boxed object type stored on the heap is transferred to the value type that is stored on the stack. Unlike Boxing, the Unboxing has to be done explicitly. The object type is explicitly cast to the value type, and the value type must be same as value the object type is referring to.

Let’s understand Unboxing with an example :
int i = 24;
object ob = i; // Box the integer type n into object type ob.
int j = (int) ob; // Unbox the integer value stored in object type ob to integer type y.

Difference between WHERE and HAVING in SQL

1)  Apart from SELECT queries, you can use WHERE clause with UPDATE and DELETE clause but HAVING clause can only be used with SELECT query. For example following query, which involve WHERE clause will work but other which uses HAVING clause will not work :

update DEPARTMENT set DEPT_NAME="NewSales" WHERE DEPT_ID=1 ;  // works fine
update DEPARTMENT set DEPT_NAME="NewSales" HAVING DEPT_ID=1 ; // error



2) WHERE clause is used for filtering rows and it applies on each and every row, while HAVING clause is used to filter groups in SQL.

 
3) One syntax level difference between WHERE and HAVING clause is that, former is used before GROUP BY clause, while later is used after GROUP BY clause.



4) When WHERE and HAVING clause are used together in a SELECT query with aggregate function,  WHERE clause is applied first on individual rows and only rows which pass the condition is included for creating groups. Once group is created, HAVING clause is used to filter groups based upon condition specified.