What is the difference between strong and weak references?

We can understand weak reference and strong reference with the help of a windows application which have 1 windows project file and 1 class library. The class library has a very simple class Class1 which has 1 function called callme() which return “I am the real class”. We are invoking the callme() function through Windows application’s Form1’s button click event (through adding reference of class library in windows application and after that creating the object of Class1 and through that object we can invoke callme() function). Now if we copy the .exe and .dll files to another location and then we run the .exe file its running properly.

Now if we create another .dll with same class name, same method name, and if we will replace with existing .dll  with the new one then the .exe will invoke new .dll and the .exe file not complaining about it because .exe file only identify the .dll file by namespace name, class name and method name, this is called as weak reference

Weak Reference- Weak Reference is where the .exe file identifying the .dll files by namespace name and class name only.

Strong Reference- Strong Reference is where the .exe file identifying the .dll files not only by namespace name and class name only, but also by a strong name.

Strong Name- Strong name is a unique name which is produced by the combination of version no, culture information, public key and digital signature.

To create a strong name we have to right click on class library and select properties and we will go to the “Signing*” tab and check on “Sign the assembly” and then “Choose a strong key name file” then by selecting <New..> in the dropdownlist a popup will open where we can give “Key file name” and “Protect my key file with a Password”(if require).When we “Sign the assembly” it creates a .snk file which will associated with the .dll file, and now the bonding between .exe file and .dll file is not only limited upto namespace name and class name but also by a strong name which is a unique identifier.

Now if we want to copy the .exe and .dll files from in another location and if we replace the .dll and then we run the .exe file it will not run properly and it’s giving us an error that “Public key token is not valid”

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s