Constructor explanation C# - c#

I am little confused with constructor use so can someone please explain me on simple example. I give example of a simple code and in it I don't know why to use constructor instead of the way I am using.
I made class for calculation
public class Calculation
{
private double a;
private double b;
private double c;
private double d;
private double e;
public Calculation ()
{
}
public double e (double a,double b,double c,double d)
{
e = (a * 10) / (b * c * d);
return e;
}
}
Now I made an instance of this class in my windows form
public partial class Form1 : Form
{
public Calculation example;
public Form1()
{
InitializeComponent();
example = new Calculation();
}
private double A = 200;
private double B = 45;
private double C = 55;
private double D = 20;
private void button1_Click(object sender, EventArgs e)
{
string E = (example.e(A, B, C, D).ToString());
label1.Text = E;
}
Whats are the advantages and disadvantages of this method that I used? Is there more efficient way to do this with the constructor?
I am confused because everything is public either way, you can't instantiate private class and private constructor.

You would want to use a constructor with parameters instead of a method with parameters when you want to create an instance of your class and at the same time set its internal state.
Constructors have the task of initializing the object's data members and leaving the resulting object in a valid state.
You should learn more about concepts of OOP (object-oriented programming). Start by reading about Methods, Classes, Constructors, Setters and Getters to learn the basics then go from there.

Related

I can't use the variable in c# (Windows Form App)

Im working a project in C# Visual Studio 2019
If i try to use i get this error:
Error CS0103 The name 'x' does not exist in the current context
Error CS0103 The name 'y' does not exist in the current context
How can i use variables normaly?
{
public Game()
{
InitializeComponent();
}
private void Game_Load(object sender, EventArgs e)
{
int x = 10;
int y = 11;
}
private void Lapkérés_Click(object sender, EventArgs e)
{
if (x > y)
{
MessageBox.Show("x bigger");
}
}
}
Because x and y are declared in a method, so they are termed local in the Game_Load Method. that means this two-variable exists in this Method and you can use those variables the entire Method's scope and the nested code blocks inside the method, but they won't exist after the method’s execution is over (in this case after the execution of Game_Load). so they won't be accessible from anywhere else.
Otherwise, if you want the variables to be used for the entire class, you should declare them out of a method and at the class-level. like this :
class Test
{
int x;
int y;
private void TestMethod()
{
x = 10;
y = 11;
}
}
so the variables will be available for all non-static methods declared in the class.
Because they don't exist in that context. The variables are defined, and thus exist, only in the Game_Load method.
It sounds like you want them to be class-level members instead:
class Game
{
private int x;
private int y;
public Game()
{
InitializeComponent();
}
private void Game_Load(object sender, EventArgs e)
{
this.x = 10;
this.y = 11;
}
private void Lapkérés_Click(object sender, EventArgs e)
{
if (this.x > this.y)
{
MessageBox.Show("x bigger");
}
}
}
In this way they will be created when the instance of the class is created and will survive within that instance. Any method in the class can access its instance's values for those variables.
Note that multiple instances of the Game class would each have their own values in those variables. Other scopes exist which may be relevant in other cases. For example, the values could be static or you may store them externally in a file or database to persist outside the running application, etc.
(For this particular, likely contrived example you don't even really need Game_Load, you can just set the values directly at the class-level when declaring them or in the Game() constructor. But I'll assume the plan here is to introduce more logic in Game_Load which otherwise wouldn't belong at the class level or in the constructor.)
For your variables to be accessible, they must be initiated.
Here they are in a private function which must be called this function before making your if condition
you have made x and y local variables for the Game_Load function.
You will need to move them to instance variables by declaring them at the class level, rather than the method level.
Define the variables at class level
{
private int x;
private int y;
public Game()
{
InitializeComponent();
}
private void Game_Load(object sender, EventArgs e)
{
x = 10;
y = 11;
}
private void Lapkérés_Click(object sender, EventArgs e)
{
if (x > y)
{
MessageBox.Show("x bigger");
}
}
}
You need to declare your variables (x and y) as private variables in your class but outside the function.
Here, you only declare x and y in the Game_Load function.
Also, don't use 'é' in your function name it won't work.
I think that the answers here answer everything, but I would like to clarify some things. The variables that you in the Game_Load method are only seen by the method. They cannot be accesed anywhere else. In order to be able to use them everywhere in your class, you have to declare these two variables in the class outside of any methods:
class SomeClass{
private int x; //can be accesed anywhere in the class
private int y; // can also be accesed anywhere in the class
public Game()
{
InitializeComponent();
}
private void Game_Load(object sender, EventArgs e)
{
x = 10;
y = 11;
}
private void Lapkérés_Click(object sender, EventArgs e)
{
if (x > y)
{
MessageBox.Show("x bigger");
}
}
}
When you declare your variables as private, they can be accesed anywhere in the class. Just make sure that you do not declare these variables in your methods.

How to change my global variable in other function? c#

I want to change the global integer- amount, by make his value as 'c' value, how can i do that?
public static class Globals
{
public const int amount = 5689;
}
private void button1_Click(object sender, EventArgs e)
{
int b = int.Parse(textBox2.Text);
int c = Globals.amount - b;
textBox3.Text = c.ToString();
**Globals.amount = c;** // ***how do i set this?***
}
Since amount is defined as a constant, you can't change it.
You can, however change it if you made it a non-constant static variable instead.
public static int amount = 5689;

Object passed to method not maintaining reference in C#

I am trying to build a dummy exercise for my own interest.
I have one form (form1) with two textboxes (textBox1, textBox2) and a button.
When I click the button, I want to add the numbers passed to the textboxes.
Now, I am trying to complicate things by introducing an Interface with the signatures of the appropriate methods to do the addition (ICalculate) and a class (Calculations) which implements the interface.
Then I have another class called Calc which gets initiated from Form1 by passing an ICalculate object and 2 integers (a,b) in its constructor.
Furthermore, the Calc class has a method (addition()) for adding the two integers, using the ICalculate object and the two integers instantiated at the constructor of the class and display the result on a messagebox.
The problem is that the compiler throws an error saying that the ICalculate object has not been initialized (Object reference not set to an instance of an object.)
The code is the following:
public interface ICalculate
{
int add(int x, int y);
int sub(int x, int y);
}
class Calculations : ICalculate
{
public int add(int a, int b)
{
return (a + b);
}
public int sub(int z, int k)
{
return (z - k);
}
}
class Calc
{
private ICalculate _nc;
private int _x, _y;
public Calc(ICalculate nc, int a, int b)
{
var _nc = nc;
_x = a;
_y = b;
}
public void addition()
{
MessageBox.Show(_nc.add(_x, _y).ToString());
}
}
}
The Form1 Code is the following:
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var a = Int32.Parse(textBox1.Text);
var b = Int32.Parse(textBox2.Text);
var c = new Calc(new Calculations(), a, b);
c.addition();
}
}
Any help appreciated !
The problem is in the constructor of the Calc class.
Specifically, this row:
var _nc = nc;
You should remove the var:
_nc = nc;
What happens is that once you have the var keyword you are actually creating a local variable called _nc in the constructor, and assign the value of nc to it, so the class member called _nc is never initialized.
The compiler (tested on VS 2013) should issue a warning for this:
Field '<your namespace here>.Calc._nc' is never assigned to, and will always have its default value null

how i can send two or more than two arguments to private methods of class using properties

hi i have class with one private method. i am trying to send two values(two arguments) to its method using property but its not working.some time it gives compiler error and some time wrong answer(logical error).
class sum
{
private int add (int a, int b)
{
return a+b;
}
private int ts;
public int MyProperty
{
get { return ts; }
set { ts = add(value,value);
}
}
Code in main Class
private void button5_Click(object sender, EventArgs e)
{
sum sumv = new sum();
sumv.MyProperty=2;
int sumj = sumv.MyProperty;
MessageBox.Show(sumj.ToString());
}
Well the short answer is: you can't send two parameters to a property setter.
Properties are just meant to be synthaxical sugar to avoid having to implement java/c++-like accessors (getProperty(), setProperty()...).
That being said, you can totally do some work on the value you get in the property's setter (like checking if it is in a certain range of values, or even modifying it...). But value is the only value you will ever get by using it.
And public methods aren't inherently bad, else we wouldn't have the mean to use them in the first place. I'd like to know where you've seen that.
If you want to practice in OOP concepts - your way isn't correct.
This class much better suitable for OOP:
public class Adder
{
public int Result {get; private set;} // private setter allow you to hide this member.
public void Sum(int value1, int value2)
{
Result = value1 + value2;
}
}
There seems to be a lot of confusion here caused by OOP principles. Here's a couple of ways you could achieve what you want.
Make your method public. There's nothing wrong with doing this as you are not storing anything and there's nothing to encapsulate:
public class Adder
{
public int Add(int value1, int value2)
{
return value1 + value2;
}
}
Pass in your parameters in the class constructor:
public class Adder
{
private int _value1;
private int _value2;
public Adder(int value1, int value1)
{
_value1 = value1;
_value3 = value2;
}
public int Add()
{
return _value1 + _value2;
}
}
There is a rule of some sort about this :
If you have private method that you want to expose to other classes
but you don't want to make it public then create a public delegate
and pass your method with this delegate
Your property can be of delegate type. In this case the get method will return delegate. This delegates contains your method add, that you can run :
class sum
{
private int add (int a, int b)
{
return a+b;
}
public Func<int, int, int> MyProperty
{
get { return add; }
}
}
And use it like this :
private void button5_Click(object sender, EventArgs e)
{
sum sumv = new sum();
int sumj = sumv.MyProperty(5, 10);
MessageBox.Show(sumj.ToString());
}

Why is it useful to inherit from EventArgs?

I don't understand why inheriting from EventArgs is useful.
public class ClickedEventArgs : EventArgs
{
int x;
int y;
public ClickedEventArgs (int x, int y)
{
this.x = x;
this.y = y;
}
public int X { get { return x; } }
public int Y { get { return y; } }
}
In the code above, how can I use this inheritance?
I also want to learn how I can call this code block from default.aspx
Are you asking why it's useful to derive from EventArgs in the first place? I have to say that with C# 1 it didn't make a lot of sense, because of the way delegate conversion worked - but as of C# 2 it's more sensible. It allows an event handler to be registered with an event even if it doesn't care about the details of the event arguments.
For example:
void LogEvent(object sender, EventArgs e)
{
Console.WriteLine("Event sent from " + sender);
}
...
textArea.KeyPress += LogEvent;
This works even though Control.KeyPress is an event of type KeyPressEventHandler. C# and .NET don't mind that the signature of LogEvent doesn't exactly match the signature of KeyPressEventHandler - it's compatible enough.
Admittedly this would still be feasible if we didn't have EventArgs at all (you could just use object) but given the EventArgs class and the pattern, it makes sense to derive your own event arguments from EventArgs.
What is really important here is that you can easily UPGRADE your event later to have MORE details and don't break existing decoupled listeners.
Here is a example of how you might use your code:
public class MyClass () {
public event EventHandler<ClickedEventArgs> ClickedEvent = delegate {}; //Register the event
protected void SomethingWasClicked(int x, int y) {
ClickedEvent(this, new ClickedEventArgs(x,y)); //Invoke the event that is subscribed to
}
}
public class AnotherClass () {
public AnotherClass () {
MyClass mClass = new MyClass();
mClass.ClickedEvent += new EventHandler(mClass_clickedEvent);
}
protected void mClass_clickedEvent(object sender, ClickedEventArgs e) {
//Retrieve the X parameter that was passed from the MyClass instance
int x = e.X;
}
}

Categories