.comment-link {margin-left:.6em;}

Wednesday, February 23, 2005

 

Passing a value Type ByVal Tricky Question ?

this is a small tricky question : ( Very IMP )

what is the Console.WriteLine  going to print ?

public class Reference                       public struct Value

{                                                        {

    public int i;                                            public int i;              //Not Private

    public int Prop                                       public int Prop

        {                                                            {

        get  {return i;}                                          get  {return i;}

        set  {i = value;}                                        set  {i = value;}

        }                                                            }

}                                                        }

   

classExample

{

    private Reference_r; // Reference type

    private Value_v; // Value type

    public Example()

    {

        _r = new Reference();

        _v = new Value();

    }

    public Reference RefProp

    {

    get  {return _r;}

    set  {_r = value;}

    }

    public Value ValueProp

    {

    get  {return _v;}

    set  {_v = value; }

    }

}

class Program

{

    static void Main(string[] args)

    {

        Example e = new Example();

        e.ValueProp.i = 4;

          Console.WriteLine(e.ValueProp.i);  // what is going to be printed after this line ?

    }

}

take care of the line :  e.ValueProp.i = 4;

let's divide this line , e.ValueProp is going to return an instance of the Value Struct , then we go ahead and change the "i" field on this struct

so first part is getting the Value instance from the ValueProp :  

Value v1 = e.ValueProp;         //is V1 is going to take a copy of the returned Value instance or going to reference this instance ?

                                                   // of course it is going to take a copy . coz this is a value type byVal assignment

SO

v1.i = 4;                                       //is going to change the "i" field on the copied Instance not the original . so the Console.WriteLine should Print 0

                                                    // but the Compiler detects this issue and throw a compile error .

 


Comments:
Fantastic Entry . this means that .NET still lack the feature of getting reference or a clone to any type either it is a reference or a value type.
 
Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?