user2837961
user2837961

Reputation: 1555

c# Passing parameter by value

I have created a class which passes a string parameter in the constructor. I change the value of the parameter in the constructor. When the control is back on my original class, the value is not changed. I expect it to change - please help

        string NewNodeName = "";
        AddNode NewNodeFrm = new AddNode( NewNodeName);

        NewNodeFrm.ShowDialog();
        if (NewNodeFrm.DialogResult.Equals(true))
        {
           MessageBox.Show(NewNodeName);
        }

In class called

public partial class AddNode : Window
{
    private string NodeName;

    public AddNode(ref string ANodeName)
    {
        NodeName = ANodeName;
        NodeName = "Fred";

        InitializeComponent();
    }

Upvotes: 0

Views: 119

Answers (3)

Jeb
Jeb

Reputation: 3799

It's worth baring in mind that string is an immutable reference type which is implemented in a way to give it the occasional appearance of being a value type. So when you do this:

NodeName = ANodeName;

You're creating a copy, not a reference.

If you did something like this:

        Foo NewNodeName = new Foo();
        AddNode NewNodeFrm = new AddNode(ref NewNodeName);
        MessageBox.Show(NewNodeName.ToString());

And:

    public class Foo
    {
        private int _a = 0;

        public int BAR { get { return _a; } set { _a = value; } }
    }

    public class AddNode
    {
        private Foo NodeName;

        public AddNode(ref Foo ANodeName)
        {
            NodeName = ANodeName;
            NodeName.BAR = 30;
        }
    }

Then this would be fine, the changes would be visible to the caller since you're working on the same object in the AddNode method. In fact you don't need to use the "ref" keyword (pass by reference) in this case as we're not creating a new instance of Foo in the AddNode method.

Upvotes: 2

Noel
Noel

Reputation: 587

You can overcome using an object . Maybe pass in this:

Public class NodeName
{

       public string Name{get;set;}

}

Then in your constructor set a local variable and change the name

public AddNode : Window
{
    Private NodeNme name;
    Public  AddNode(NodeNme name)
   {
        this.name = name;
        this.name.Name = "Fred";
   }
}

Because your are passing and storing a ref type this will reflect the changes inside your class and in your consumer.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234665

When you write NodeName = "Fred"; you are changing what NodeName is referring to. That's because NodeName itself is not a ref string.

Upvotes: 4

Related Questions