Variable Declaration and Assignment

What is difference between these two statement? if variable is declared and assign value in following two ways

String sValue = (String)GridView1.DataKeys[GridView1.SelectedIndex].Value;
String sValue = GridView1.DataKeys[GridView1.SelectedIndex].Value.ToString();

Questions by ranbiragarwal

Showing Answers 1 - 12 of 12 Answers

amackail

  • Oct 15th, 2009
 

The only difference between the two is in the second example you are actually
doing the boxing of the value type into a reference type onto the stack. As
every type in C# is derived from the type 'object', they all have the .ToString
method. The .ToString method does this boxing (or copying) for you. If you were
to look into the IL code you would see that a copy of the initial value type is
created as a reference type when the toString method is used with a line that
looks something like this


IL_0004: box [mscorlib]System.Int32.


In short, these two actions are the same to the CLR.

  Was this answer useful?  Yes

hdkhanna

  • May 17th, 2010
 

First statement:
String sValue = (String)GridView1.DataKeys[GridView1.SelectedIndex].Value;

The above statement uses type casting (explicit) to convert the value to string.

Second statement:
String sValue = GridView1.DataKeys[GridView1.SelectedIndex].Value.ToString(); 

The above statement uses the method ToString() to convert the value to string.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions