pass reference of derived type failing

I'm trying to pass an object by reference so that I can modify some values inside the object. Unfortunately I get a compile time error with the code.

Here are the relevent code snippits:

Matching_Communications__c newComm = new Matching_Communications__c();
SetCommonProperties( ref newComm );

void SetCommonProperties( ref sObject customSFObject ) {

which yields:

C:\...\SalesForcePlayground\DoMatch.aspx.cs(113,21): error CS1502: The best overloaded method match for 'DoMatch.SetCommonProperties(ref SForceAPI.sObject)' has some invalid arguments
C:\...\SalesForceApiPlayground\DoMatch.aspx.cs(113,44): error CS1503: Argument '1': cannot convert from 'ref SForceAPI.Matching_Communications__c' to 'ref SForceAPI.sObject'

I have also tried:

void SetCommonProperties( ref object customSFObject ) {

Which gives a similar error:

Argument '1': cannot convert from 'ref SForceAPI.Matching_Communications__c' to 'ref object'

I have tried casting the object to the base class, even casting it to object, but nothing worked.

I do have an alternate solution by creating a generic class with a static method SetCommonProperties, but I would like to know why this particular case failed.

Any ideas Am I missing something in the language about passing derived types by reference

Thanks in advance.

Bryan



Answer this question

pass reference of derived type failing

  • Big Bob Cooley

    Just to clarify further, http://msdn.microsoft.com/library/default.asp url=/library/en-us/csref/html/vclrfPassingMethodParameters.asp states:

    "A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the value of a class member. However, you cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for a new class and have it persist outside the block. To do that, pass the parameter using the ref (or out) keyword."

    It sounds like you are not wanting to change the actual object reference inside SetCommonProperties(), just the data in the object, so you probably don't need to use ref.

    Genevieve Orchard



  • Kyle Anderson

    see this thread as this problem is referenced there.

    with ref keyword you should pass exact type. you could use this sample to achieve this

    Vehicle testCar = new Car();
    DoSomething(testCar);

    void DoSomething(ref Vehicle par)
    {
    par.Model =
    "asd";
    }

    Note: if these are reference types it is not neccesary explicitely specify ref keyword as they are passed by reference

    hope this helps



  • pass reference of derived type failing