Sunday, September 13, 2009

Grant access to your Assembly from COM objects

This is a very common occasion where we need to expose a .NET assembly to COM applications, so that the COM application can communicate with .NET assemblies. Here I am going to create a .NET Assembly and expose it from COM.

Your COM Exposed .NET class :

Let us create the Class which I need to expose to COM.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace ComVisibleObject
{
[Guid("EB7F73B0-AF1F-4595-8CE8-849D3745E862")]
public interface IComVisibleObject
{
string GetString();
void SetString(string value);
}

[Guid("DF8B1227-68EC-4F76-8C79-D20574C21B56")]
[ComVisible(true)]
public class ComVisibleObjectEx : IComVisibleObject
{
private string element = string.Empty;

public string GetString()
{
return element;
}

public void SetString(string value)
{
element = value;
}

}
}

Here I have created an Interface called IComVisibleObject which might be used to create the class. Please note, it is not mandatory to create the interface.

To Uniquely Identify each class we placed GuidAttribute to each of them. The class ComVisibleObjectEx is exposed to COM using ComVisibleAttribute set to true.

After your class is created in Class Library, Right click on Project - > Go to Properties and select Register for COM interop.
Again Under the signing Tab Select Sign the Assembly. In the Choose key file combobox select New. Choose Filename, Username and password.. The Strong name key will be created automatically.

Now Build the project. Say the dll produced is ComVisibleObject.dll. Use GacUtil to put it in Global Assembly Cache. Use this :
gacutil -i ComVisibleObject.dll

If its successful it will confirm "Assembly successfully added to the cache”.

To add it from COM applications, you need to register assembly using regasm tool.Use

regasm ComVisibleObject.dll
After registration is successful, it will say "‘Types registered successfully".

Now let us create your COM application. For simplicity I use vbs. You can easily create an original VB application to test this as well

Dim object
set object = CreateObject(”ComVisibleObject.ComVisibleObjectEx”)
MsgBox(”Created the object.”)
defaultText = object.GetString()
MsgBox(”Default text length : ” & Len(defaultText))
object.SetString(”My new string”)
newText = object.GetString()
MsgBox(”New text is ” & newText)

Finally save the file as Example.vbs.
Open Command prompt and type

cscript Example.vbs

You will see the messageboxes show the text.

Monday, August 3, 2009

UnCommon C# keywords - A Look

 This is really a weird topic to start with. But still I would like to give you an insight on some of the uncommon things that you may not have noticed while doing programming. I have framed them in 2 sections.

1st one for Undocumented Keywords, which you will not find anywhere, not even in MSDN Documentation, which are not listed to intellesense menu in visual studio.
2nd one for Documented Keywords which are uncommon or just being introduced to C#. Documented keywords which are uncommon can be found over MSDN.I have also made a sample application where I have given some demonstration of each of the topics mentioned here in this article. If you want to test these, please download the sample application from here :



Thursday, June 11, 2009

Compress Response

It is obvious that we need to compress our response while passing to the client. Compress requests and response are always increases performance of sites. Nowadays, almost 99 percent of the browsers supports either Gzip or Deflate compression or both. So if we can check if accept-encoding header is present and return compressed response to the client, then we have just improved our site performance. Just take a look on the code below :

public static void doCompression()
{
HttpContext context = HttpContext.Current;
HttpRequest request = context.Request;
string acceptEncoding = request.Headers["Accept-Encoding"];
HttpResponse response = context.Response;
if (!string.IsNullOrEmpty(acceptEncoding))
{
acceptEncoding = acceptEncoding.ToUpperInvariant();
if (acceptEncoding.Contains("GZIP"))
{
response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
response.AppendHeader("Content-encoding", "gzip");
}
else if (acceptEncoding.Contains("DEFLATE"))
{
response.Filter = new DeflateStream(context.Response.Filter, CompressionMode.Compress);
response.AppendHeader("Content-encoding", "deflate");
}
}
response.Cache.VaryByHeaders["Accept-Encoding"] = true;
}


Here we are checking if the Request header contains [“Accept-Encoding”]. Based on the encoding it supports we filter the response using GZipStream / DeflateStream which are available in System.IO.Compression namespace. Thus the response will be compressed.
Only this will not help the client to render your page properly. You need to add the Content-Encoding header to the response, so it can decompress the response in the client properly. We add Response header “Accept-Encoding” so that request is also made from now using the same encoding it is sending the data.

Thursday, February 26, 2009

Linq Basics

Hi Folks,
Hope you all are enjoying this blog. Its a long time since I last posted in this blog. As technology is getting richer and richer, I must write something new in this post. Right now it is definitely a phase of all of us to take the new .NET framework 3.5 with having lots of flexibility in both coding as well as technology.
Lets start with Whats New in 3.5?

You know the three concepts that was added with .NET 3.0 :
1. Windows Communication Foundation (.NETs first attempt to merge all the existing remoting concepts into a single Service Oriented Architecture).
2. Windows Presentation Foundation (Improvement in presentation layer so that user interface could be enhanced very easily.
3. Workflow foundation ( Easily create workflows to generate business logics, Managing object lifecycles / persistent object storage )

After that after the introduction of .NET 3.5 language enhancements are also made so that programmers could make use of technology more easily to enhance their code easily. The recent changes to C#.NET are :
1. LINQ ( Language Integrated Query)
2. Implicitly Typed Interface
3. Object and Collection Initializers.
4. Extension methods
5. Anonymous Types
6. Lamda Expressions
7. Auto implemented properties.

LINQ
Linq is the Microsoft's first attempt to integrate queries into language. We know, it is really easy to find data from sql objects simply writing a query while its somewhat hectic when we want to do the same thing in a DataTable or Lists. Generally we will have to loop through every elements to find the exact match, if there is some aggregation we need to aggregate the values etc. Linq provides an easy way to write queries that can run with the in memory objects. Let us demonstrate that :

Suppose we want to find all the employees whose age is above 50. From database if we want to do this we would write :
select * from employees where age > 50
In case of doing this from code, let us suppose we have a list of employees which have a property age in it. Now before linq we will write :
List<employee> filteredList = new List<employee>();
foreach(Employee emp in employees) // where employees is a list
{
If(emp.Age > 50)
filteredList.add(emp)
}


If we use linq we would write like :
List<employee> filteredList = new List<employee>();
var filterEnumerable = from emp in employees
where emp.Age >50 select emp;
filteredList = filterEnumerable.ToList();


Thus we see how easy to write a linq expression. Let us demonstrate it a bit more.

From emp in employees : This is the temporary elements for each query loop. By from emp we mean we are creating a var of emp and set the objects that comes from employees list one after another.
where emp.Age >50 select emp: means we are imposing restriction on the emp, so that if its age is more than 50 then select emp.

Lambda Expressions:
C# also provides lamda expressions to have short hand writing of linq expressions using Extension methods to static Enumerable Class. This extension methods are added to every Enumerable objects.
We can write the same filterList Linq Expression using Lamda Expression like this :
var filterEnumerable = employees.Where<employee>(emp => emp.age > 50);
For every linq expression there is a corresponding Lambda expression.

What is VAR?
Var is implicitly typed Interface which comes very handy in case of anonymous types. Suppose we write like:
var customers = from c in customersjoin o in orders on c.CustomerIDequals o.CustomerID into cofrom o in co.DefaultIfEmpty(emptyOrder)select new { c.Name, o.OrderDate, o.Total };
This returns a new type object to an enumerable lists.

Every linq statements returns an IEnumerable list of objects. You may now think what var signifies. Actually it is a implicitely typed interface. It assigns its type based on the object it finds. Thus if we set var i= 10 it will signify that variable i is an Integer variable.

Now let us delve more into Linq with examples, Linq comes with lots of Operators:
  • Restriction operators
  • Projection operators
  • Partitioning operators
  • Join operators
  • Concatenation operator
  • Ordering operators
  • Grouping operators
  • Set operators
  • Conversion operators
  • Equality operator
  • Element operators
  • Generation operators
  • Quantifiers
  • Aggregate operators
Now Let us take each of them one by one.
First I have created three lists :
List employees = new List();
List employees1 = new List();
List orders = new List();

employees.Add(new Employee { age = 40, name = "Basob" });
employees.Add(new Employee { age = 34, name = "Abhishek" });
employees.Add(new Employee { age = 65, name = "Souvik" });
employees.Add(new Employee { age = 65, name = "Ayan" });
employees.Add(new Employee { age = 68, name = "Raj" });
employees1.Add(new Employee { age = 68, name = "Pallab" });
employees1.Add(new Employee { age = 55, name = "Swarup" });
employees1.Add(new Employee { age = 68, name = "Ranjit" });
employees1.Add(new Employee { age = 68, name = "Bratin" });
orders.Add(new Order { empName = "Raj", itemName = "Pen" });
orders.Add(new Order { empName = "Souvik", itemName = "Pencil" });
orders.Add(new Order { empName = "Raj", itemName = "Rubber" });
Now Let us use these lists to demonstrate each of the operators.

Restriction Operator:
Restriction operator can be applied by using Where clause. Example of Where clause:
var filterEnumerable = from emp in employeeswhere emp.age > 50select emp;ORvar filterEnumerable = employees.Where<employee>(emp => emp.age > 50);

This filters out Employees by age greater than 50.

Projection Operator:
With the word projection, I mean Select statements. Every linq elements should have projection in it.
var iNames = from i in employees select i.name;ORvar iNames = employees.select<employee,string>
Here IEnumerable of Name is returned.

Partitioning using Take /Skip operators
Take can be used when we take first N elements in a list, skip will take the elements after N.
var MostAged2 = employees.OrderByDescending(i =>i.age).Take(2);
var AllButMostAged2 =employees.OrderByDescending(i => i.age).Skip(2);

Takewhile and skipwhile operator will select from a list based on a delegate passed in.

var allWithfourwordlength = employees.SkipWhile<employee>(r => r.name.Length > 4);


Join Operators:
Join operators have 2 parts. The outer part gets results from inner part and vice versa so returns the result based on both
var filterEnumerable = from emp in employeesjoin ord in orders on new { Name = emp.name }equals new { Name = ord.empName }select emp;ORvar filterEnumerable = employees.Join<employee,Order, string, Employee>(orders, e1 => e1.name,o => o.empName, (o, e2) => o);
Here we are joining employees and order based on the names passed in

Concatenation Operator :
The Concatenation operator concats two sequence.
var items = ( from itEnt in _itemListwhere itEnt.Category.Equals("Entertainment")select itEnt.ItemName).Concat(from it2 in _itemListwhere it2.Category.Equals("Food")select it2.ItemName).Distinct();
This will concat categories of Entertainment and Food. Distinct oprator can also be used to evaluate only distinct elements in resultset.
OrderBy / ThenBy
Orderby/ThenBy can be used to order dataresults.

var orderItems = from emp in employees orderby emp.name,emp.age descending;
var orderItems =employees.OrderBy(i => i.name).ThenByDescending(i => i.age);
Here the ordering is done by name and then decending by age.

GroupBy Operator :

This is used to group elements.
var itemNamesByCategory =from i in _itemListgroup i by i.Category into gselect new { Category = g.Key, Items = g };
This gets all the categories and items grouped by category. Well this grouping seems to be a little tricky for me. Let me make you understand what exactly is the way. Here while we are grouping, we are taking the group into g(which is a IGrouping). The g will have a key, which holds the grouped data, you can add multiple grouping statement. If you want to have a having clause, its just the where clause will do. Just like the example below:
var filterEnumerable2 = from emp in employees
where emp.age >65 //Normal Where clause works on all items
group emp by emp.age into gr
where gr.Key > 40 // Grouped where clause similar to Having Clause
select new { aaa = gr.Key, ccc=gr.Count(), ddd=gr.Sum(r=>r.age), bbb = gr };
Here in the example, I have returned the aggregate functions like sum, count etc which you can find from group data.

Distinct / Union / Intersect / Except Operators :

Union operator produces an union of two sequences
var un = (from i in _itemListselect i.ItemName).Distinct().Union((from o in _orderListselect o.OrderName).Distinct());
Intersect operator produces an intersection of two sequences.
var inter = (from i in _itemListselect i.ItemID).Distinct().Intersect((from o in _orderListselect o.OrderID).Distinct());
Except operator produces a set of difference elements from two sequences.
var inter = (from i in _itemListselect i.ItemID).Distinct().Except((from o in _orderListselect o.OrderID).Distinct())

Well there are lots more to tell you about LINQ. I am stopping it here. If you want more,
Read the Full Article.

Sunday, October 26, 2008

Best Practices of Memory Usage

Lets talk about memory management in practical sense. While we do programming, we often do use of memory in excess of what we need. Generally memory is cheap when you are working with Desktop applications, but while you are doing an ASP.NET application that handles lots of memory of server, excess use of memory and Session may sometimes bring with lots of pain. So let us discuss about best practices of Memory Management so that we can reduce memory wastage.

There is some odd behaviour of the programmers to give memory to the member variables inside a class. This is really odd, because this may sometimes loose extra amount of memory usage unnecessarily. Just take a look on the code below:

public class BadUse
{
private SqlConnection con = new SqlConnection();
private DataSet ds = new DataSet("MyData");

public BadUse() {}
public BadUse(string connectionString)
{
SqlConnection = new SqlConnection(connectionString);
}
public BadUse(SqlConnection con)
{
this.con = con;
}
}
If you see the code above, we are definately loosing unnecessary memory of our system. For every class before any calls been made, even before the calls to the constructors, object member initializer is called. Which executes and gives memory to all the member variables. Now in the class demonstrated avove, we are making an object of SqlConnection during the initialisation. After that, we are either calling the default constructor or creating object within the constructor. Thus without making use of the already created object, I am creating object again, and thus loosing memory.
Best Practice :

public class GoodUse
{
private SqlConnection con = null;
private DataSet ds = null;

public SqlConnection Connection // Better to use Properties
{
get
{
if(this.con == null) // Always check whether there is an existing object assigned to member
this.con = new SqlConnection();
return this.con;
}
set
{
if(value == null || this.con !=null)
{
this.con.dispose(); // Clears out Existing object if member is assigned to Null
this.con = null; // Always better to assign null to member variables
}
if(value !=null) this.con = value;
}
}
public GoodUse() {}
public GoodUse(string connectionString)
{
this.Connection = new SqlConnection(connectionString); //Assignes new object to null member
}
public GoodUse(SqlConnection con)
{
this.con = con;
}
}

Thus from the above code we are clear, it is always better to have properties rather than accessing objects directly. This gives you an interface to modify each calls later. Similar to this, it is always better to use Event Accessors for accessing Events.
private MyDelegate MyEvent;
public MyDelegate CheckEvent
{
add
{
lock(this); // Better to invoke a lock before adding EventHandler to the Event
MyEvent + =value;
}
remove
{
lock(this); // Use lock before removing Event Handler also
MyEvent -= value;
}
}
In case of VB.NET we have a third block too, for RaiseEvent, which will be invoked whenever some Event is raised from within the code.

Use Using and Try/Catch block for Resource Cleanups
Going like this, It is always better to use Using block whenever you use Disposable Objects. In case of all constructs .NET provides, Try /Catch block and Using block generally calls Dispose() function automatically whenever object which implements IDisposable comes out of the block. Thus use of Try/Catch block and Using block is always better in .NET. See the example below:

public void Execute(string connectionstring, string sql)
{
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Dispose();
}


In the above code snippet, we are simply creating an object of SqlConnection and SqlCommand. It is true that both objects implements IDisposable. Thus it is better to rewrite the code like below:
public void Execute(string connectionstring, string sql)
{
using(SqlConnection con = new SqlConnection(connectionstring))
{
using(SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
cmd.ExecuteNonQuery();
}
}
}

Thus rewriting like this will automatically call Dispose method, but we dont need to call it directly. Therefore, it is better to make use of Using statement for quick resource deallocation.

You can also use Try/ Catch block similar to this as below
try
{
SqlConnection con = new SqlConnection(connectionstring);
try
{
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
cmd.ExecuteNonQuery();
}
catch {}
finally
{
cmd.Dispose();
}
}
catch(){}
finally
{
con.Dispose();
}
}


Next, it is always better to use "as" or "is" rather than casts. Means while we want convert types we should use "as" keyword rather than implicitely typecasting.

object o = new SqlConnection();
SqlConnection con = o as SqlConnection; // Better to use this
SqlConnection con = CType(o, SqlConnection); // Not always better

In the above two statements, if you use the second one for conversion rather than opting for the first, it will throw error if Ctype cannot convert object ot that type and also if there is null in o. But in case of using 'as' statement it will not throw error, but rather it will assign null to con.

Use Structure while calling a Function

Good to call functions with small numbers of arguments. Generally it takes a lots of time to send multiple arguments rather than sending a large object directly to the function. Try creating a Structure for all those arguments that you want to send, and send the structure directly. As structures are sent using value type, we can also minimize boxing.
public void Callme(int x, int y, string zy)
public void Callme(argumentStruct st) // Better in performance

Thus it would be always better to send a structure rather than discrete objects.

Better to have one Large Assembly rather than having a number of Small Assemblies

Similar to what I have told you earlier, it will be a good practice to have one large assembly with lots of namespaces in it rather than creating a number of small class libraries, one for each namespaces. Even microsoft does this by creating all assemblies within mscorlib.dll, thus reducing load of metadata, JIT compile time, security checks etc.

Better to avoid Threading if it is not unavoidable

Generally use of many threads may lead to lack of performance as each threads takes a lot of memory from the main process to run independently. Is it seem strange to you? Its true. In cases when you need quick processing, you can use threading, but it will increase memory consumption.
Do use of ThreadPool when you create Threads.

Avoid use of ArrayList or HashTables, rather go for Linked Arrays when you need to insert data randomly

Even like you, I am also surprized to say this. Actually, if you see the internal structure of an ArrayList or HashTables, they are just a wrapper of Array. Whenever you insert an object to these structure, it redims all the allocations, and shifts them manually. ArrayList is an Array of objects while HashTable is an Array of Structure.
Another strange thing is, for ArrayList or HashTables, Extents are made in modulus of 4. That means whenever it needs memory it always allocates in a multiple of 4. LinkLists, Generic Lists, LinkedArrays are always better in performance than Collection Objects when you need random insertion. Collections are better when you need to just add data and show data in sequence.

I will talk about memory management more, but need some more experience for writing. Thanks for reading.

Thursday, October 9, 2008

Memory Management in .NET

In .NET memory is managed through the use of Managed Heaps. Generally in case of other languages, memory is managed through the Operating System directly. The program is allocated with some specific amount of memory for its use from the Raw memory allocated by the Operating system and then used up by the program. In case of .NET environment, the memory is managed through the CLR (Common Language Runtime) directly and hence we call .NET memory management as Managed Memory Management.


Allocation of Memory

Generally .NET is hosted using Host process, during debugging .NET creates a process using VSHost.exe which gives the programmer the basic debugging facilities of the IDE and also direct managed memory management of the CLR. After deploying your application, the CLR creates the process in the name of its executable and allocates memory directly through Managed Heaps.

When CLR is loaded, generally two managed heaps are allocated; one is for small objects and other for Large Objects. We generally call it as SOH (Small Object Heap) and LOH (Large Object Heap). Now when any process requests for memory, it transfers the request to CLR, it then assigns memory from these Managed Heaps based on their size. Generally, SOH is assigned for the memory request when size of the memory is less than 83 KBs( 85,000 bytes). If it is greater than this, it allocates memory from LOH. On more and more requests of memory .NET commits memory in smaller chunks.

Now let’s come to processes. Generally a process can invoke multiple threads, as multi-threading is supported in .NET directly. Now when a process creates a new thread, it creates its own stack, i.e. for the main thread .NET creates a new Stack which keeps track of all informations associated with that particular thread. It keeps informations regarding the current state of the thread, number of nested calls etc. But every thread is using the same Heap for memory. That means, Heaps are shared through all threads.

Upon request of memory from a thread say, .NET allocates its memory from the shared Heap and moves its pointer to the next address location. This is in contrast to all other programming languages like C++ in which memory is allocated in linked lists directly managed by the Operating system, and each time memory requests is made by a process, Operating system searches for the big enough block. Still .NET win32 application has the limitation of maximum 2GB memory allocation for a single process.

32 bit processors have 32 bits of address space for locating a single byte of data. This means each 2^32 unique address locations that each byte of data can locate to, means 4.2 billion unique addresses (4GB). This 4GB memory is evenly distributed into two parts, 2 GB for Kernel and 2 GB for application usage.


De- Allocation of Memory

De - allocation of memory is also different from normal Win32 applications..NET has a sophisticated mechanism to de-allocate memory called Garbage Collector. Garbage Collector creates a thread that runs throughout the runtime environment, which traces through the code running under .NET. .NET keeps track of all the accessible paths to the objects in the code through the Graph of objects it creates. The relationships between the Object and the process associated with that object are maintained through a Graph. When garbage collection is triggered it deems every object in the graph as garbage and traverses recursively to all the associated paths of the graph associated with the object looking for reachable objects. Every time the Garbage collector reaches an object, it marks the object as reachable. Now after finishing this task, garbage collector knows which objects are reachable and which aren’t. The unreachable objects are treated as Garbage to the garbage collector. Next, it releases all the unreachable objects and overwrites the reachable objects with the Unreachable ones during the garbage collection process. All unreachable objects are purged from the graph. Garbage collection is generally invoked when heap is getting exhausted or when application is exited or a process running under managed environment is killed.

Garbage collector generally doesn’t take an object as Garbage if it implements Finalize method. During the process of garbage collection, it first looks for the object finalization from metadata. If the object has implemented Finalize(), garbage collector doesn’t make this object as unreachable, but it is assigned to as Reachable and a reference of it is placed to the Finalization queue. Finalize is also handled by a separate thread called Finalizer thread which traces through the finalizer queue and calls the finalize of each of those objects and then marks for garbage collection. Thus, if an object is holding an expensive resource, the finalize should be used. But there is also a problem with this, if we use finalize method, the object may remain in memory for long even the object is unreachable. Also, Finalize method is called through a separate thread, so there is no way to invoke it manually when the object life cycle ends.

Because of this, .NET provides a more sophisticated implementation of memory management called Dispose, which could be invoked manually during object destruction. The only thing that we need is to write the code to release memory in the Dispose and call it manually and not in finalize as Finalize() delays the garbage collection process.

Cost of Finalize in your Program:

Now let us talk about the cost that you have to bear if you have implemented indeterministic approach of .NET and included Finalize in your class. To make it clear you must know how GC works in CLR:

Generation 0 object means the objects that we have declared after last garbage collection is invoked. 1st Generation objects means which is persisting for last 1 GC cycle. Likewise 2nd Generation objects and so on. Now GC does imposes 10 examinies for 0 to 1 generation objects before doing actual Garbage Collection. For 1 to 2 Generation objects it does 100 examinees before collecting.

Now lets think of Finalize, an object that implemented Finalize will remain 9 cycle more than it would actually collected. If it still not finalized, it would move to Geeration 2 and have to go through 100 examinees to be collected. Thus use of Finalize is generally very expensive in your program.

IDisposable implementation:


For Deterministic approach of resource deallocation, microsoft introduced IDisposable interface to clear up all the resources that may be expensive.

Let us take an example :

Protected virtual void Dispose(bool isDisposing)
{
if(IsDisposed) return;
if(isDisposing)
{
// Dispose all Managed Resources
}
IsDisposed = true;
GC.SuppressFinalize(this);
}

Now let us explain,
The first line indicates an if condition statement, Here I have checked if the object is already disposed or not. This is very essential, as in code one can call dispose a multiple times, we need to always check whether the object is already disposed or not. Then we did the disposing, and then made IsDisposed to true.
Now GC.SuppressFinalize will suppress the call to finalize if it is there. This is because, if the user already disposed the object and cleared up all the expensive resources using deterministic approach of deallocation, we dont need the GC to wait to call Indeterministic Finalize method during the Garbage Collection process.

For local objects, we can call dispose directly after using the object. We can also make use of Using block or try/catch block for automatic disposal of objects.

Note: In case of USING, you must remember it works only with the objects that Implements IDisposable. If you use object that dont have implemented IDisposable interface in using block, .NET will through error.

Friday, September 19, 2008

Difference Between DirectCast and TryCast

Generally while doing our program in VB.NET or any language whatsoever, we come across some situation where we are in Dilemma of having more than one solution of a single problem. We think thoroughly of our knowledge base, search the Internet to get which one will be the best logic discuss with seniors or otherwise do random choice or anything. As a programmer, I always do face the problem. Let us take the example of casting in .NET.

We know, VB.NET always include Microsoft VisualBasic Namespace for your application internally, and you cannot remove the reference to that or even you don't find the namespace in the References list. This is because while you do programming with Visual Basic, your application would be enriched with some of the functionalities that Microsoft VisualBasic namespace have within your program. Take for instance Val, CStr, CInt etc. All of them are written inside Microsoft VisualBasic namespace and is included automatically in our program. They are are acting as language helpers in your program.

DirectCast:

Let us try to write one of this language helpers ourself.

Public Function CustomCInt(ByVal value as Object) as Integer
if typeof Value is Integer then
Dim i as Integer = CustomCInt(Value)
Return i
End Function

After viewing the above code you must be laughing like hell on what I have done with this. Actually my motive is to show you how difficult is to write a helper yourself without using CLR supported casting feature. Here comes the case of DirectCast. While using CInt, CStr, or CType you are actually calling a function which does similar to what I have written. Means it first checks if the type is convertable or not through Typeof Operator and then casts to appropriate Type.
DirectCast is the Simple CLR typecasting feature which you can use when you are sure about the cast. It avoids the sequence of checking in the helper Functions. Now you can write your own Helper Function like this:

Public Function CustomCInt(ByVal value as Object) as Integer
If TypeOf value is Integer then
Dim i as Integer = DirectCast(value,Integer)
Return i
End if
End Function

Now it looks great, Isnt it. Actually this is how .NET helpers are made, CType checks if the object corresponds to the Type specified and then DirectCast it to return the Converted Type Data. DirectCast is the most simple and CLR supported TypeCast feature that will cast properly if it is with appropriate type or otherwise throws an error.

TryCast:

Now going further, Lets start with TryCast. After knowing DirectCast you may wonder what exactly the TryCast is. Actually TryCast operator of VisualBasic is equivalent to 'is' operator of C#. TryCast is useful in some situations too.
Let us take the following example

Public Function CustomCheck(ByVal value as Object) as IDBConnection
If TypeOf value is IDBConnection then
Dim i as IDBConnection = DirectCast(value,IDBConnection)
Return i
End if
End Function

In this example, we are telling the CLR to check the type of Value that we passed to the Function using TypeOf function in the If statement. If it enters into the IF we can confirm that the value implements IDBConnection. But CLR doesn't knows it. Thus on the very next step, it will check if the value actually an implementation of IDBConnection again. Thus we are running redundant code. Using TryCast we can avoid that.
We may write

Dim i as IDBConnection = TryCast(value,IDBConnection)


This will direct the CLR to check if value implements IDBConnection and if so, it will convert it directly. Thus we removed Redundant code.
TryCast will store nothing if it cannot cast the value. In case of using TryCast for primitive types, it will store the value of initialization as output if it cannot convert. For Instance, conversion to integer will give you Zero(0) etc.

Hope you understand the two simple operators of Visual Basic. Don't forget to Comment on the topic. Thanks.

Author's new book

Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!