yogeshkmrsoni
yogeshkmrsoni

Reputation: 315

Is there any automatic way to sync values of objects

IDE: VS 2010, c# .net winforms

Hi, I am having 3 objects obj1 obj2 and obj3, and obj1 some values are initiated and obj2 some values are initiated and I want in obj3 as final object which will contain values of both obj1 and obj2, see below examples: (the values will be merged only if it is not null or 0.

AClass obj1 = new AClass();
obj1.value1 = 14;
AClass obj2 = new AClass();
obj2.value2 = 15;
//I want
AClass obj3 = new AClass();
obj3 = obj1 + obj2;  // this is not available

//I want to get obj3.value1 = 14 and obj3.value2 = 15 (initiated)

Is there any faster or predefined way to doing this.

Upvotes: 1

Views: 63

Answers (3)

DevEstacion
DevEstacion

Reputation: 1977

You can do operator overloading in c#, here is the code

    private class AClass
    {
        public int Value { get; set; }

        public static AClass operator +(AClass a, AClass b)
        {
            return new AClass
            {
                Value = (a != null ? a.Value : 0) + (b != null ? b.Value : 0)
            };
        }
    }

Consume it like this.

        AClass a = new AClass() { Value = 5 };
        AClass b = new AClass() { Value = 3 };
        AClass c = a + b;

Upvotes: 0

Karim AG
Karim AG

Reputation: 2193

You can use a technique in C# called "Operator Overloading", here is an example:

class AClass
    {
        public int value1 { get; set; }
        public int value2 { get; set; }

        public AClass()
        {
        }

        public AClass(int value1, int value2)
        {
            this.value1 = value1;
            this.value2 = value2;
        }

        public static AClass operator +(AClass obj1, AClass obj2)
        {
            return new AClass(obj1.value1, obj2.value2);
        }
    }

private void Form1_Load(object sender, EventArgs e)
    {
        AClass obj1 = new AClass();
        obj1.value1 = 14;
        AClass obj2 = new AClass();
        obj2.value2 = 15;
        AClass obj3 = new AClass();
        obj3 = obj1 + obj2;
        label1.Text = obj3.value1.ToString(); // Output 14
        label2.Text = obj3.value2.ToString(); // Output 15
    }

And here is a reference about Operator Overloading.

Hope this helps.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502066

No, there's no built in support for merging... and unless the types of value1 and value2 are int?, you may not be able to tell the difference between "not initialized" and "initialized to 0". (If they're properties, you could give them custom setters and remember which properties have been set that way.)

Rather than using +, I would suggest you create your own static method to return the merged instance:

AClass obj3 = AClass.Merge(obj1, obj2);

You'd need to write the logic within that method, of course. We can't easily give sample code for that without knowing more about your requirements and types.

Upvotes: 2

Related Questions