PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 10, 2022

[FIXED] How do I assign by "reference" to a class field in C#?

 July 10, 2022     c#, field, parameters, reference     No comments   

Issue

I am trying to understand how to assign by "reference" to a class field in C#.

I have the following example to consider:

 public class X
 {

     public X()
     {
         string example = "X";

         new Y(ref example);

         new Z(ref example);

         System.Diagnostics.Debug.WriteLine(example);
     }

 }

 public class Y
 {

     public Y( ref string example )
     {
         example += " (Updated By Y)";
     }

 }

 public class Z
 {
     private string _Example;

     public Z(ref string example)
     {

         this._Example = example;

         this._Example += " (Updated By Z)";
     }
 }

 var x = new X();

When running the above code the output is:

X (Updated By Y)

And not:

X (Updated By Y) (Updated By Z)

As I had hoped.

It seems that assigning a "ref parameter" to a field loses the reference.

Is there a way to keep hold of the reference when assigning to a field?


Solution

No. ref is purely a calling convention. You can't use it to qualify a field. In Z, _Example gets set to the value of the string reference passed in. You then assign a new string reference to it using +=. You never assign to example, so the ref has no effect.

The only work-around for what you want is to have a shared mutable wrapper object (an array or a hypothetical StringWrapper) that contains the reference (a string here). Generally, if you need this, you can find a larger mutable object for the classes to share.

 public class StringWrapper
 {
   public string s;
   public StringWrapper(string s)
   {
     this.s = s;
   }

   public string ToString()
   {
     return s;
   }
 }

 public class X
 {
  public X()
  {
   StringWrapper example = new StringWrapper("X");
   new Z(example)
   System.Diagnostics.Debug.WriteLine( example );
  }
 }

 public class Z
 {
  private StringWrapper _Example;
  public Z( StringWrapper example )
  {
   this._Example = example;
   this._Example.s += " (Updated By Z)";
  }
 }


Answered By - Matthew Flaschen
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing