Posted by: Zeeshan Amjad | September 13, 2011

Field overloading


We already saw one example how to overload function on return type using MSIL here because MSIL supports this. In fact we can do the same with field. We can’t create more than one field with the same name but with different data type. Here is one program to try to do field overloading.

Code Snippet
class Program
{
    static int data = 10;
    static float data = 20.0f;

    static void Main(string[] args)
    {
        Console.WriteLine(data);
    }
}

 

This is invalid C# program, because we can’t create two fields with same name even though they have different data type.

But we can do this with MSIL. Here is a code to define fields in MSIL.

Code Snippet
.field private int32 data
.field private float32 data

 

When we are accessing these fields then we have to define the data type too, therefore we can access each element individually. Here is a code to set the diferent values in each variable.

Code Snippet
ldc.r4     10.
stsfld     int32 MyClass::data

ldc.r4     20.
stsfld     float32 MyClass::data

 

Here is complete MSIL program to demonstrate the field overloading concept.

Code Snippet
.assembly function{}

.class public MyClass
{
    .field private int32 data
    .field private float32 data

    .method static void start()
    {        
        .entrypoint
        .maxstack 1
        
        ldc.r4     10.
        stsfld     int32 MyClass::data
        
        ldc.r4     20.
        stsfld     float32 MyClass::data
        
        ldsfld     int32 MyClass::data
        call       void [mscorlib]System.Console::WriteLine(int32)
        
        ldsfld     float32 MyClass::data
        call       void [mscorlib]System.Console::WriteLine(float32)
        
        ret
    }
}

 

The output of the program is

10

20

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

Categories

%d bloggers like this: