简体   繁体   中英

C# Error when initialize a variable in a different public class

I am trying to initialize 2 different variables in a public class but when I initialize the second one, it gets the property (Name in this example) of the first one. After I set the name of the second one. The first variable changes its name property to the second name. For example, when I execute the code:

    //Initialization and set of first var
    findLineToolA.Name = "findLineToolA";
    findLineToolB = null;
    //After findLineToolB = new CatFindLineTool();
    findLineToolA.Name = "findLineToolA";
    findLineToolB.Name = "findLineToolA";

    //After findLineToolB.Name = "findLineToolB";
    findLineToolA.Name = "findLineToolB";
    findLineToolB.Name = "findLineToolB";

    public class CatFindLineTool 
    {
            private static string _name;

            public string Name
            {
                set
                {
                    _name = value;
                }
                get
                {
                    return _name;
                }
            }
    }
public class CatFindCornerTool 
{
    public CatFindLineTool findLineToolA;
    public CatFindLineTool findLineToolB;
    public CatFindCornerTool()
    {
     findLineToolA = new CatFindLineTool();
     findLineToolA.Name = "findLineToolA";
     findLineToolB = new CatFindLineTool();
     findLineToolB.Name = "findLineToolB";
    }
   }

I hope someone can help me to figure out why the properties mix up when initialize multiple variables. I guess it is because there is an important concept about C# class that I am ignoring. Thanks in advance.

You have declared the _name field to be static . This makes it a 'global' or 'shared' entity across all instances of the class - hence changes to one instance will affect all instances.

Just remove the static keyword and your code should work as intended.

Better use Auto-property. You don't have to create a private member for name.

A public property

public string Name {get;set;}

will automatically create the required private property for you internally.

Your issue is already addressed by Jens Meinecke

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM