Jump to content

Adding to classes

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
Davide

Davide

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 506 posts
Hello,
let's say i have a class, and it stores two or three variables. I declare the two variables of this class:

MyClass value1 = new MyClass();
MyClass value2 = new MyClass();

I want to know how i can add them like this:

MyClass Result= new MyClass();
Result = value1 + value2;

What do i need to write in my class so i can perform this?

Thank you!
Are you a newbie programmer trying to learn C#? Check out my small tutorial: Visual C# Programming Basics

#2
veda87

veda87

    Programmer

  • Members
  • PipPipPipPip
  • 126 posts
All you have to do is to overload the + operator

 class Class1
    {
        int num;
........// constructor.... blah blah blah things....
.......
public static Class1 operator +(Class1 source1, Class1 source2)
        {
            Class1 temp = new Class1();
            temp.num = source1.num + source2.num;
            return temp;
        }
}
this will do.....

#3
Davide

Davide

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 506 posts
Thanks, that worked!
Are you a newbie programmer trying to learn C#? Check out my small tutorial: Visual C# Programming Basics