Girish Jain on .Net Framework

I will be writing about my favorite technology which is Microsoft .Net Framework and how to use it to improve developer productivity

System.Object Members

clock January 30, 2011 14:18 by author Girish Jain

System.Object Class Members

I recently started with my blog site and hence, I decided to post something from my old learning notes (of course after polishing it), thinking it could be useful to someone. I am going to talk about System.Object class. It is the ultimate base class for all types in CLR (except pointer types which are not convertible to object instance). This class defines methods which can be utilized by instances of value as well as reference types. Value types in CLR are those types which inherit from either System.ValueType or System.Enum and these two classes in turn derive from System.Object, therefore, all the methods defined in Object class are available to instances of value types as well as reference types. Object class defines the following operations:

Note: It is important to note that unlike reference type instances, value type instances are stored sans object header in memory and hence, calling virtual methods on value type instances would result in the instance being boxed and so on. Boxing/Un-boxing is performance costly operation and hence, should be avoided.

 

public virtual bool Equals(object obj);

This method is defined as virtual and therefore, can be overridden by type deriving from object class. It should be overridden to define custom implementation for establishing equality with another object instance. In its default implementation, this method does a reference equality check for reference types and bitwise equality for value types.

Reference equality means the object references that are compared refer to the same object. Bitwise equality means the objects that are compared have the same binary representation.

A derived type might override the Equals method to implements the value equality. Value equality means the compared objects have the same value even though they have different binary representations. For example, consider two decimal objects that represent the number 1.10 and 1.1000. The decimal objects don’t have bitwise equality because they have different binary representations. However, the objects have value equality because the numbers 1.10 and 1.1000 are considered equal for the comparison purpose.

Usage Scenarios: You can use the equality operator (==) or call the Equals method to compare two instances for equality. The call to equality operator would be determined at the compile time depending upon the type of receiver and argument to it, whereas the call to Equals method is a virtual call and would be determined at runtime depending upon the type of receiver, and therefore, would impact the performance. Therefore, it would be advisable to use the equality operator where you wish to use the default CLR implementation for equality and Equals method should be called only when the type you are comparing for equality has its own implementation for Equals method.

Also, calling the Equals method on value types will have far more performance issues, as CLR would need to use reflection to determine the method to be called as value type instances don’t have object header like reference type instances and therefore, you should avoid calling virtual methods on value type instances.

 

public static bool Equals(object objA, object objB);

Similar to the earlier method in terms of functionality, but this variant is a static method and takes both the objects as parameters

 

public virtual int GetHashCode();

This instance method returns the hash code for the current object.

Usage Scenarios: It is useful in situations where the object is being maintained in collections like HashTable or other data structure. A derived type can override this method and provide its own custom implementation.

 

public Type GetType();

It returns the System.Type instance for the current instance.

Usage Scenario: It is useful in situations where we need to pass the type instance as parameter or need to work with the reflection API.

 

protected object MemberwiseClone();

It’s a protected method, hence, available to all the classes which inherit from System.Object. This is useful in the cloning operation and the default implementation shallow copies the instance i.e. creates bit-by-bit copies of value type members and reference type members are copied but the referred data is not.

 

public static bool ReferenceEquals(object objA, object objB);

It’s a static method which compares two references and returns true if the two point to same object instance.

 

public virtual string ToString();

It’s a virtual method which can be overridden by the derived class to provide one’s own custom description of an object instance. Ideally, a class must override this method to return some meaningful text which associates with the object instance.

 

Vande Mataram!

(A salute to motherland)

P.S. In addition to blogging, I use Twitter to share tips, links, etc. My Twitter handle is: @girishjjain




Interfaces Extended

clock January 29, 2011 22:26 by author Girish Jain

Interfaces Extended

Today I am going to write about my learning experience related to interfaces which I discovered while making one of design decision for a project. From the good old days of C++, we are used to think an interface as a contract defining *operations* which the implementer must implement and the consumer can easily consume (using the known contract i.e. interface). These operations were to be implemented by the class which implements the interface.

This raised a question whether we can defined fields, properties, or events as part of interface? Lets try to find answer to this question.

Note: I have never worked on C++, other than for academic purpose, and am not sure if it provides some direct mechanisms to define events as part of interface definition, you can assume I was not so good in academics. Therefore, I am writing this purely from CLR perspective.

Field/Property in Interface Definition

You cannot define a field as a member of an interface because it serves no purpose i.e. if you really want to expose a (field like) member to the consumers of your class, you should expose it through property construct. A property is a logical construct which wraps the data members of object whereas a field is a physical construct which contains the actual data. You cannot define a physical construct in a contractual definition because a contractual definition is logical. It logically binds with the implementing class. Therefore, you cannot define fields as members of interfaces. Similarly, a property being a logical construct can be defined as interface member.

Events in Interface Definition

In CLR, you can define events as part of interface definition. Defining an event as an interface member declares a contractual binding that the class which implements this interface will have an event of the given delegate type. Logically, this correctly relates to the communication of objects in object oriented world. This establishes the communication channel between two objects which don’t know each other, but the interface contract. For example, an interface IServer can define an event, namely ServerStarted and the class which implements this interface will raise this event every time it starts the server for listening requests. All other objects which are interested in receiving notification of a server being started can register with the object for receiving the same. There could be an array of objects which could potentially be interested in knowing when a particular server starts without the server knowing them all. This facilitates the communication and results in loose binding between the objects i.e. the number of objects interested in receiving the notification could increase or decrease without affecting the server object. Therefore, declaring events as interface member helps in communication between objects and should be used whenever required. Events in interface definition helps define the contract and establish the formal communication channel between the implementer and consumer classes with loose binding and therefore, strongly recommended to use.

 

So interfaces are a very strong concept and I would encourage everyone to use its capabilities wherever possible.

Vande Mataram!

(A salute to motherland)

P.S. In addition to blogging, I use Twitter to share tips, links, etc. My Twitter handle is: @girishjjain




CLR Versions Compatibility

clock January 25, 2011 19:40 by author Girish Jain

CLR Version Compatibility

Let us try to execute application built against one version of CLR, on another CLR version, to understand forward and backward compatibility of CLR versions.

 

You can control the CLR version to be used for executing your application using application configuration file and supportedRuntime element, as follows:

 

Forward Compatibility (v1.1 to v2.0)

Let’s modify the application configuration file for CLR v1.1 application and try to execute it on CLR v2.0 and check the output.

Configuration changes:

 

Now executing the application, produces following:

As can be seen, CLR 1.1 applications are forward-compatible with CLR v2.0*

 

Forward Compatibility (v2.0 to v4.0)

Let’s modify the application configuration file for CLR v2.0 application and try to execute it on CLR v4.0 and check the output.

Configuration changes:

Now executing the application, produces following:

As can be seen, CLR 2.0 applications are forward-compatible with CLR v4.0*

Forward Compatibility (v1.1 to v4.0)

Let’s modify the application configuration file for application CLR v1.1 application and try to execute it on CLR v4.0 and check the output.

Configuration changes (basically same as we did in last step):

Now executing the application, produces following:

As can be seen, CLR 1.1 applications are forward-compatible with CLR v4.0*

Backward Compatibility (v2.0 to v1.1)

Executing CLR v2.0 application on CLR v1.1 produces following errors:

First the following message appears:

Clicking on Ok button shows the following:

And then the following exception in the command prompt:

Hence, CLR v2.0 applications are NOT backward compatible with CLR v1.1

 

Backward Compatibility (v4.0 to v2.0)

Similarly, while executing CLR v4.0 application on CLR v2.0, we get the following exception:

Hence, CLR v4.0 applications are NOT backward compatible with CLR v2.0

 

To summarize forward/backward compatibility of CLR versions:

  1. CLR v1.1 apps are forward compatible with CLR v2.0*

  2. CLR v1.1 apps are forward compatible with CLR v4.0*

  3. CLR v2.0 apps are forward compatible with CLR v4.0*

  4. CLR v2.0 and v4.0 apps are NOT backward compatible i.e. app built against a version of CLR, cannot run on the older version of CLR (it throws BadImageFormatException)

 

[*]When we talk about forward compatibility, it is important to note that the newer version of CLR would have introduced some breaking changes by modifying base class library and hence, to determine whether your application is fully compatible, you need to actually test your application on the newer CLR version before concluding on the compatibility.

 

Vande Mataram!

(A salute to motherland)

P.S. In addition to blogging, I use Twitter to share tips, links, etc. My Twitter handle is: @girishjjain




CLR Versions

clock January 13, 2011 15:57 by author Girish Jain

Today, I want to talk about different CLR versions which exist and our understanding about them. Let’s build a small application and build it against different versions of .Net framework. We will use vanilla source code to output “Hello World” and the underlying (CLR) framework version used.

Source Code:

using System;

public class HelloApp
{
    static public void Main()
    {
        Console.WriteLine("Hello World!!");
        Console.WriteLine();
        Console.WriteLine(string.Format("Framework version used : {0}", Environment.Version));

        Console.ReadLine();
    }
}

Let’s build the application against different versions of .Net Framework (using Visual Studio).

In order to compile the application you need to open Visual Studio 20XX Command Prompt and use the following command:

csc HelloApp.cs

 

It will generate HelloApp.exe and you can check the metadata of the generated assembly by using following command:

ildasm HelloApp.exe

Now let’s check output of the above program with respect to different versions of .Net Framework and the metadata changes.

Visual Studio 2003 (.Net Framework 1.1)

Compiling the application and executing it from VS 2003 command prompt produces the following output:

VS2003 CLR 1.1 Execution

As we can see, (and as expected) it is targeting CLR v1.1. Let’s check the metadata of the generated assembly:

CLR 1.1 Assembly Metadata

It shows the Metadata version and the version of mscorlib being targeted. We can see it is targeting CLR v1.1, which is what one would expect.

 

Visual Studio 2005 (.Net Framework 2.0)

Compiling the application and executing it from VS 2005 command prompt produces the following output:

VS2005 CLR 2.0 Execution

As we can see, (and as expected) it is targeting CLR v2.0. Let’s check the metadata of the generated assembly:

CLR 2.0 Assembly Metadata

We can see it is targeting CLR v2.0, which is what one would expect.

 

Visual Studio 2008 (.Net Framework 3.0/3.5)

Compiling the application and executing it from VS 2008 command prompt produces the following output:

VS2008 CLR 2.0 Execution

Surprise!! It is targeting CLR v2.0, something which I did not expect. Let’s check the metadata of the generated assembly:

CLR 2.0 Assembly Metadata for VS2008

We can see it is targeting CLR v2.0, which confirms the reason for the above output. Why would an application compiled using Visual Studio 2008 (which was using .Net Framework 3.5) target .Net Framework 2.0? Before answering this question, let’s see the output with Visual Studio 2010.

 

Visual Studio 2010 (.Net Framework 4.0)

Compiling the application and executing it from VS 2010 command prompt produces the following output:

VS2010 CLR 4.0 Execution

As we can see, (and as expected) it is targeting CLR v4.0. Let’s check the metadata of the generated assembly:

CLR 4.0 Assembly Metadata

We can see it is targeting CLR v4.0, which is what one would expect.

So, we saw the application targeting CLR v1.1, 2.0, and v4.0 but, where did CLR v3.0/3.5 go? In fact, CLR v3.0/v3.5 never existed. In reality, .Net Framework 3.0 release contained additional set of libraries such as WCF, WF, and WPF which were all built upon existing CLR v2.0. The underlying CLR was not changed at all as part of .Net Framework v3.0 release. None of the core libraries were changed and hence the CLR version remained same. CLR version has now changed with .Net Framework v4.0 release as there are substantial changes to Base Class Library (BCL) in CLR v4.0. Basically, CLR skipped version from v2.0 to v4.0. There was no CLR v3.0 or v3.5.

In my next post, we will see applications compatibility between CLR versions i.e. how applications targeting a particular version of CLR work with another version (i.e. forward and backward compatibility)

Vande Mataram!

(A salute to motherland)

P.S. In addition to blogging, I use Twitter to share tips, links, etc. My Twitter handle is: @girishjjain




Property Type and Name can be Same

clock November 14, 2010 23:29 by author Girish Jain

Often while writing code we struggle thinking of unique names to be assigned to our Class, Properties, Variables, etc. When we create an instance of a class, we mostly prefix the reference variable name with *obj* and so on. We are so used to this concept in our mind that we need to give a unique name to our instances, properties, etc that we forget an important feature supported in CLR. You can have the name of your property same as the type of your property and you need not think of some unique name each time you are working with the same object but reuse the CLR type name itself. For example:

/*

In the below code, you can notice that the PropertyTypeAndNameSame has a property called TestData and its type is also TestData. This example shows that you can have the name of your property same as the type of your property and you need not think of some unique name each time you are working with the same logical entity but reuse the type name.

*/

 

using System;

public class TestData
{
    public string Name { get; set; }
}

public class PropertyTypeAndNameSame
{
    private TestData _data;

    public PropertyTypeAndNameSame()
    {
        this.TestData = new TestData();
    }

    public TestData TestData
    {
        get { return this._data; }
        set { this._data = value; }
    }

    public static void Main()
    {
        PropertyTypeAndNameSame obj = new PropertyTypeAndNameSame();
        obj.TestData.Name = "Test";

        Console.WriteLine(obj.TestData.Name);
        Console.ReadLine();
    }
}

Vande Mataram!

(A salute to motherland)

P.S. In addition to blogging, I use Twitter to share tips, links, etc. My Twitter handle is: @girishjjain




About the author

Girish Jain works on Microsoft .Net framework technologies and is a big fan of WPF, WCF, and LINQ technologies. He is currently based in India with his wife and a daughter. When not spending time with family, Girish enjoys creating small tools, utilities, frameworks to improve developer productivity.

Sign In