Home > database >  Problem with C# ref when used in parent class
Problem with C# ref when used in parent class

Time:01-15

I have the abstract class

  public abstract class BaseType
  {
    public BaseType(int offset)
    {
      TestRef(ref offset);
    }

    protected abstract void TestRef(ref int offset);
  }

and a derived type,

  public class DerivedType : BaseType 
  {
    public DerivedType(int offset) : base(offset)
    {
      Console.WriteLine($"ctor: increasing offset: {  offset}");
    }
    
    protected override void TestRef(ref int offset)
    {
      Console.WriteLine($"TestRef: increasing offset: {  offset}");
    }
  }

and a main where I instantiate a derived type:

  public static void Main()
  {
    var dt = new DerivedType(0);
  }

I assumed that since TestRef takes a reference to the offset that I would have seen the change TestRef addition. In other words I would have expected the output bellow,

TestRef: increasing offset: 1
ctor: increasing offset: 2

but I'm getting

TestRef: increasing offset: 1
ctor: increasing offset: 1

What I've done wrong here?

CodePudding user response:

If I understand your question correctly, to achieve the behaviour you want you need to consistently pass the integer by reference in all calls, as follows:

public abstract class BaseType
{
    public BaseType(ref int offset)
    {
        TestRef(ref offset);
    }

    protected abstract void TestRef(ref int offset);
}

public class DerivedType : BaseType
{
    public DerivedType(ref int offset) : base(ref offset)
    {
        Console.WriteLine($"ctor: increasing offset: {  offset}");
    }

    protected override void TestRef(ref int offset)
    {
        Console.WriteLine($"TestRef: increasing offset: {  offset}");
    }
}

public static void Main()
{
    var dt = new DerivedType(ref 0);
}

CodePudding user response:

The constructor argument which is passed to the base class via base(offset) is passed by value to the base class and not by reference. You can’t pass a constructor argument by reference.

  •  Tags:  
  • Related