Nicole Bauer
Nicole Bauer

Reputation: 1

Changing value in class from form and reading it from another class, possible?

I must admit I'm quite the beginner as far as coding goes.

Right now I want to change a boolean value in a class by pressing a button in the Main Form.

But I also want to read the changed value from another class.

Is this even possible ? I'm using C# btw.

Because right now I have the problem that using Class1 class = new Class1(); creates unique versions of the class for the form1 and the class calling it.

Upvotes: 0

Views: 131

Answers (1)

jacob aloysious
jacob aloysious

Reputation: 2597

You could try two options

1. Using static Property: By using a static property only one copy of it exists and its not object specific.

Example:

public class Class1
{
    public static bool MyBoolProperty { get; set; }
}

You could use it as

        //Set value 
        Class1.MyBoolProperty = true;

        //Get value
        var currentBoolVal = Class1.MyBoolProperty;

2. Using singleton instance: Here only one object is created.

Example:

public class Class1
{
    private Class1()
    {
    }

    private static Class1 _object;

    public static Class1 Instance
    {
        get
        {
            if (_object == null)
                _object = new Class1();
            return _object;
        }
    }

    public bool MyBoolProperty { get; set; }
} 

You could use it as:

        //Set value
        Class1.Instance.MyBoolProperty = true;

        //Get value
        var currentBoolVal = Class1.Instance.MyBoolProperty;

Upvotes: 1

Related Questions