Click here to Skip to main content
14,930,722 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Sir,

I read about a fact that Explicit interface methods are used so as to avoid boxing and provide compile time safety.

I tried out a code:

SCENARIO 1:
internal struct somevaluetype : IComparable
{

private int32 m_x;
public somevaluetype(Int32 x)
{
m_x = x;

}

public int32 CompareTo(object other)
{

return(m_x - ((somevaluetype)other).m_x); -------------- statement 1

}

}



static void main()
{

somevaluetype v = new somevaluetype(0);
Object o = new Object();
Int32 n = v.CompareTo(v); /// causes boxing
n = v.CompareTo(o); ///program terminates and throws invalid cast exception

Console.Readline();

}


To avoid above 2 situations i tried out the following :

SCENARIO 2:

internal struct somevaluetype : IComparable
{

private int32 m_x;
public somevaluetype(Int32 x)
{
m_x = x;

}

public int32 CompareTo(somevaluetype other)
{

return (m_x - other.m_x);

}

//// i have to complete the contract of IComparable so i need to implement its method so below:


int32 IComparable.CompareTo(Object other)
{

return m_x - ((somevaluetype)other).m_x) ; -------------- statement2

}



}

static void main()
{


somevaluetype v = new somevaluetype(0);
Object o = new Object();
Int32 n = v.CompareTo(v); /// No boxing
n = v.CompareTo(o); ////doesnt compile

Console.Readline();



}


- These 2 scenarios verify that the External interface method implementations are helpful.
- But what is the difference between statement1 and statement2?
- Statement1 causes run time exception and statement2 causes compile time error.
- and why can i not put any access modifier before an explicit interface method?
Posted

1 solution

Hello Rahul,

Statement1 :

you are using a directcast inside CompareTo function. its throws invalid cast exception
when argument is not a type of somevaluetype. i think you have to use following.


C#
public int32 CompareTo(object other)
{
    temp = other as somevaluetype;
	if(temp != null)
	   return (m_x - temp.m_x);
    return -1;
}


Statement2 :

IComparable.CompareTo method don't have any access modifiers. so its consider as private method.
you can't call it from out side. due to that following function throws an compile time error.

C#
n = v.CompareTo(o); ////doesnt compile



I have tested and implemented this code in C#.

Think this help.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900