How to Override Finalize method in C#

Being a .NET Developer, you must have basic information about Garbage Collector. Garbage Collector is a boon for .Net developers which takes care of memory management for .NET programs in the background.

But as we know that there are some limitations as well. Garbage collector can collect only managed object. So what about unmanaged objects. Garbage collector cannot clean up unmanaged object properly because these object are not limited to .NET framework and CLR does not have complete control on it. So it is developer’s responsibility to clean up unmanaged resources. It is advised to override the Finalize method (that is a virtual method in Object class) to clean up the unmanaged resources. Garbage collector calls the finalize method of each object (which has overridden Finalize method) while collection process.

So have you ever tried to override the Finalize method in C#? Let’s do that

 public class MyClass
    {
        protected override void Finalize()
        {
            // Do unmanaged resource clean up
        }
    }

For simplicity, I just override the Finalize method. Now let’s build the code.
Ohh.. The above code does not build. It gives the following errorErrorSo if you see the error, it says that do not override Finalize. Instead use destructor.

It means We cannot override Finalize directly in C#.

So what is other way? As in error it suggests to provide destructor. So let us write the destructor (destructor in any class starts with tilde (~)). So now my class looks like

    public class MyClass
    {
        ~MyClass()
        {
            // Do unmanaged resource clean up

            Console.WriteLine("In destructor");
        }
    }

Now let’s build it.
It builds successfully. Now let’s see this class using assembly Reflector.
destuctorSo here our destructor turned into Finalize method. So it means that destructor and Finalize are same in C#. But obviously while writing code in C#, it does not allow to override the Finalize method so we have only option to write destructor for that.

So don’t get confused ever if you see somewhere that say to override Finalize and you are not able to override it. Instead use destructor for that purpose.

Cheers,
Brij

How to use two different languages in a .NET Project

Did you ever try to use two languages in some of your project? Or Say you created a Class in VB.NET and used in C# code. As .NET provides us the capability to use multiple languages in same project, even it allows to inherit a VB.NET class in C# Class.If you have not tried earlier then this post will help you in getting practical examples. So Let’s move to the example

In this example, I have created two projects : one is C# Class library project and other is VB console application. My C# class looks like

    public class Person
    {
        public void Print()
        {
            Console.WriteLine("C# - Person's Print method");
        }
    }

It’s perfectly legal to inherit C# class in vb class. So here my vb class looks like

Public Class Student
    Inherits CLSCompliantCsharp.Person

    Public Sub Display()
        Console.WriteLine("I am Student VB class")
    End Sub
End Class

So here I have just added one more method Display in my vb.net class. Let’s move to main method

Module Module1
    Sub Main()
        Dim o As New Student()
        o.Display()
        o.Print()
        Console.ReadLine()
    End Sub
End Module

Let’s run it and see the output.

NormalSo it is perfectly fine and run as expected. Now let’s add one more method in my person class as

    public class Person
    {
        public void Print()
        {
            Console.WriteLine("C# - Person's Print method");
        }

        public void print()
        {
            Console.WriteLine("C# - Person's print method");
        }
    }

Now I have added one new method with same name print but it’s first letter is small letter. As we know that C# is case sensitive language so having the method with same name with different case, is perfectly legal.So lets build the C# project after making the changes So it is perfectly builds.

Now again move to the VB project and run the code.

Oh.. it throws a error as

errorAs we can see that it is giving error message that Print is ambiguous because for VB.NET Print() and print() are same while for Csharp different.

So How to deal this?

.NET provides us a way to make a library language neutral i e it defines some basic set of rules that can be applied to any library to make neutral. So if you think that your code/dll might be used by different language then you must apply an attribute to the your assembly.

The attribute is CLSCompliant

So if you want to make it a Class library CLSCompliant then add this attribute in the AssemblyInfo.cs file as

[assembly: CLSCompliant(true)]

I have added the above attribute in my C# project and now lets build it (with having two print method as earlier)

CLSComplaintWarningNow if you see that then it is showing an warning that this code is not CLS-Compliant Now you can correct it. Once you remove all the CLS-Complaint warnings and you can take a deep breath. You wont get any complaint if your code is used on any other language in .NET platform.

CLSCompliant attribute also provides more granular approach. It means if you don’t want to make the entire Class library as CLS-Compliant then you apply this attribute at class level as well. Then compiler will apply this attribute on that class only and that can be used by other language applications accordingly.

Hope you all have enjoyed this post.

Cheers,
Brij

Presented on ASP.NET MVC and Entity Framework on 18th Jan

Hello All,

It was a perfect day on 18th Jan 2014 at C# Sharp Cornet Delhi Chapter Event in Noida. The winter in Delhi was at peak and we all know (Dilli ki Sardi..) But we were enjoying the technologies with fun the entire day.  Around 70 attendees participated and learned the technology whole day. A big thanks to all the attendees, C# Corner, Co -speakers who made the day. A group click at the end of the event

IMG_2002

I took the last session of the day and discussed MVC and Entity Framework which was full of Demos. I discussed following Topics

  • Basics of ASP.NET MVC
  • Basics of Entity Framework
  • Entity Framework
    • Database First
    • Model First
    • Code First
  • Crud Operation with ASP.NET and EF
  • Custom Templates and Data Annotation
  • Authentication
  • Authentication using External Identity Provider
Please find below the presentation and Demo.
For official recap of the event click here
Again thanks a lot to you all.
Cheers,
Brij

Passing a reference type using ref keyword

In this post, I am going to talk about ref keyword in C#. You all must be knowing the basic use of this keyword. But for them who are new to this keyword or C#, will explain the basics.

ref keyword is used to pass the parameter by reference. It means the parameter references the same memory location as the original variable.

As we know that there are two type of variable in C#. One is Value type and other is Reference type. Whenever a value type variable is passed to a method, a copy that variable is created and passed to the method. So let’s see it pictorially

Passed by valueSo when the variable is updated in the called method, then initial variable is not updated but the copy variable gets updated.

Now let’s pass the parameter using ref keyword. So when we pass a value type variable using ref keyword the reference of the variable is passed and both variable names points to same memory location. So when the variable is updated it is available in both method. It can be depicted pictorially as

Pass value using refTill now we passed the value type variable. But when we send other type (reference type) variable to the method the reference is passed so when we update the object in the called method, the updated object gets available to both the method. let’s see the example

For this example,I used an instance of Class type

Typeand the example is

refLet’s come to the real question. What if we pass the instance using ref keyword. When the instance is itself a reference type then what else we get from it. Or they exactly same? Let’s see by example

refref1But if we see the above example, then we get the difference that now variable name points the reference of the reference variable name. When we update the object it updates the same memory location as earlier. By seeing the above example, it seems that there is no difference between passing the reference type variable normally and by ref keyword. But Wait !! Let’s see the screenshot

refref12Now when the UpdateName method get’s executed then what will happen. Let’s see this

refref2

So here after execution of UpdateName both variable name and myName points to null and now the object is available in memory but not accessible from any variable.

But if we pass the object without ref keyword in same method then

ref2So here variable name points to null but myName still points to that object and object is accessible.

So it means as long as we update the object by updating it’s property method etc.,it is same in both case but when we play with the variable name then it makes a difference as we have seen in the above example.

So next time when someone asks that difference by passing the a reference using ref keyword or without ref keyword then you can explain it.

Happy learning!!

Regards,
Brij

What is SecureString ?

In this post, we are going to discuss a class SecureString. Although this class is available since .NET 2.0, but I am sure, many of us would not be knowing or using it. Even I was not aware of this fantastic class few weeks ago. This class can be very useful for you if you are more concerned about your application security.

This class belongs to the namespace System.Security . This class should be used to store the data which is confidential. The text assigned to this string is by default encrypted. This data is also removed as soon as it is not required which in-turn reduces the chances of misuse.

Continue reading

Reading Event logs efficiently using C#

This post is extension is my last post on Event Viewer. Please the find the link below.

Working with EventViewer using C#

We’ll be talking about the reading event logs. In my last post I discussed about reading the event logs. But that is very slow because that loads all the event entries in memory and then iterate one by one. Say if we have around one five thousand entries in the log then it will load all the entries in memory and then allows to iterate one by one. It makes the reading of logs very slow. Also at certain point of point we might require to read the event logs on some specific criteria or want to read some specific logs then also we need to load all the events and iterate and find the required entry.

Continue reading

Working with EventViewer using C#

There are several phases of a Application . It does not end with developing the application and deploying it on production servers. Other most important part, any problem surfaces after the deployment, how quickly the problem can be be resolved and according to severity of the issue (if required) a patch can be deployed on production. Apart from this, we also want to get notified on all the issues occurred on production and accordingly analyze and take care in future releases. We can also log other details that could be useful to check the status of Application.

Continue reading

Learning checked and unchecked context

Today, I am going to discuss about one of the rarely used but very useful keywords of C# that are called checked and unchecked context. I learnt this few days back.  These keywords can be used at certain scenarios and can save you from hazardous situations. This would be more useful when you are playing with lots of data and doing lots of operations over it.

So let’s start with a quiz. Just predict the result of the following code snippet

   int value = 5000000;
   int multiplier = 2500;
   int result = value * multiplier;
   Console.WriteLine(result);

What would be the result?
12500000000?   No

It would be -384901888. But how?

Because if you check the max value of int. It is 2147483647. Now you can see that the result of multiplication is higher than this max value. So you can think that the value displayed is min value of int. Which is certainly not desirable.

And even you would not get any overflow exception. So be cautious, while selecting the data types of variable whether it is a normal or temporary variable.

By default, Arithmetic overflow and underflow exception is turned off. You can turn it in on assembly level. For this, you can go to

Project->Properties->build tab-> advanced button. So you’ll get the following screen.

Here you can check the checkbox for arithmetic overflow/underflow and now if you run the code, you will get the OverflowException.

But this got enabled at assembly level and if you want to to have at some code snippet level then first uncheck the above marked checkbox and second you need to use the checked and unchecked keyword to have this feature.

So checked and unchecked keywords are provided for these scenarios. If you want to get exception if some values overflows or underflows.

  1
   int value = 5000000;
   int multiplier = 2500;
   int result = 0;
   checked
   {
   	result = value * multiplier;
   }

So if you run the above you’ll get the overflow exception again. What actually checked does, whenever a value is assigned to primitive variable, it the checks with the variable’s max value if the value is greater/lower than the max/min value, it throws overflow/underflow exception.

The above code  that is in checked block, can also be written as

int result = checked((int)(value * multiplier));

One need to be cautious while writing checked/unchecked keyword. This code would not throw any exception.

unchecked keyword also can be used if you don’t want to have a check for overflow/underflow. the code can be written as

            int value = 5000000;
            int multiplier = 2500;
            int result = 0;
            unchecked
            {
                result = value * multiplier;
            }
            Console.WriteLine(result);

If you have enabled overflow exception check at assembly level but don’t want it at certain situations then you can use unchecked keyword.

There are few key points, one need to remember-

  • In any case, you cannot rely on user input whether you have some validation or not. So it’s always recommended that you have this check and code for handling the overflow exception. Even if you are getting from some third party services etc, then also I would recommend this check.
  • You cannot rely on the following code, generally it does not throw overflow/underflow exception.
        static void Main(string[] args)
        {
        	checked
            {
            	addition();
            }
            Console.ReadKey();
        }
    
        private static void addition()
        {
        	int value = 5000000;
        	int multiplier = 2500;
        	int result = 0;
        	result = value * multiplier;
        	Console.WriteLine(result);
        }
    

    I mean, one should write code statements in checked block. If you are calling any method from the checked/unchecked block, you cannot sure that it work as desired.

  • These checked/unchecked context works on CLR primitive types only.
  • System.Decimal is c# primitive type but not CLR. So checked/unchecked context has no effect on this.

I hope you all have enjoyed this feature if didn’t learn it earlier.

Who already aware of this feature, please share some more points that can be added here.

Cheers,
Brij

How to access internal class of one assembly to other assembly.

It’s been long since I made a new Post. I was missing it a lot. But now I’ll be here with my normal way..
Today I am sharing a small but useful learning with you all..

As we all know,  Internal classes are visible in the same assembly.  And we make it internal based on our requirement. i e when we make a class internal, it means we don’t want that code written outside the assembly, able to access it.

Normally in our projects, we have a separate project for Unit Tests. And obviously we may require to test that internal class. There may be some other requirement where you may need to expose your internal classes to some assembly. But how to access the internal classes here.

There is a concept of Friend Assembly in C#. It allows us to access the internal classes in other assembly.
Note : Only Internal classes can be exposed to other assembly. Private classes can not be made available outside the assembly.

Continue reading

Exploring Nullable types : Part 2

This is second and last part of the post on Nullable type series. You can view the first part from here

Exploring Nullable types : Part 1

In this series, I will talking certain rules that we need to take care while using Nullable type. I will be taking scenario wise.

First scenario:

Int? a=8;
object o = a;
long d = (long)c;

It will be compiled successfully but will throw and Invalid Cast Exception. Means, you cannot cast it to any other type except the underlying type which is here int although  int type can be hold by long.

Continue reading