We are already aware that if we don't define a constructor in the class, still a implicit constructor comes into picture and initializes some variables of class but we explicitly defines constructor under class so we have a chance of initializing variables of class with desired values.
Each and every class requires some initialization values foe execution so if we defined a constructor under the class we have a chance of sending our own initialization values for the class to execute and this values can be changed whenever wee create a new object for the class.
In the below below case, the four methods of the class requires the values for x and y to execute and those two variables are being initialized under the constructor so when and where we want to consume this class we can send values for x and y while creating the objects and then call all the four methods:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSharpConsole { class Math { int x, y; public Math(int x, int y) { this.x = x; this.y = y; } public void Add(int x, int y) { Console.WriteLine(x + y); } public void Sub(int x, int y) { Console.WriteLine(x - y); } public void Mul(int x, int y) { Console.WriteLine(x * y); } public void Div(int x, int y) { Console.WriteLine(x / y); } } }
No comments:
Post a Comment