Monday, September 1, 2014

passing values in Generic methods













Hello I am reading a book on C# and on the generic methods section I got this question:


How are object values passed in generic methods?


a. They are passed by value. b. They are passed by reference. c. They must be encapsulated in a property. d. They are passed during class instantiation.


the correct answer in the book is B, but after I do some checking I can verify that I can pass values by ref or without ref. so what can I be missing here?



static void Main(string[] args)
{
int iX = 1;
int iY = 2;
testig1
<int>(ref iX, ref iY);
testig2
<int>(iX, iY);
}

public static void testig1<T>(ref T valueX, ref T ValueY)
{
}
public static void testig2<T>(T valueX, T ValueY)
{
}


with an object, I still don't need to use ref keywork... maybe I making some confusion about the "reference" they are refering to. The code above and here is mine from testing.



class testObj {
public int test;
}

static void Main(string[] args)
{
testObj test
= new testObj();

test
.test = 0;
testig2
<testObj>(test, test);

}

public static void testig2<T>(T valueX, T ValueY)
{
valueX
= ValueY;

}


can you show me a sample code to explain that the awser B is the correct?


regards.




No comments:

Post a Comment