I'm a beginner in programming and I'm studying the basics.
You are trying to add up one class and display the results in another class.
I think I can pass it by argument, but I can't write the code and I can't understand it in the middle.
Please give me some advice.Thank you.
Add here
class GetValue
{
public static void Calc(int add)
{
inta = 3;
intb = 4;
add = 3 + 4;
}
}
// Displaying Values
namespacePraceticeConsoleApp
{
class program
{
static void Main (string[]args)
{
GetValue value = new GetValue();
}
}
}
Give the arguments to add up and return the result in a return statement.
For static methods, you do not need to create an instance with new.
I think there are many other ways to do it, but here is an example of how to do it as a basic way.
using System;
class Calc
{
Received public static int Add (inta, intb) // 2 arguments
{
return a+b;// return the result added
}
}
namespacePraceticeConsoleApp
{
class program
{
static void Main (string[]args)
{
Console.WriteLine (Calc.Add(3,4)); // Add using the Calc class Add method.
}
}
}
(I'm about to learn & haven't touched it for a while)but) If I were you, I would write as follows.
Omit Using System;//namespace description
class GetValue
{
public static void Calc(inta, intb) // Receive the number you want to add...
{
int result = a+b; // Add…
Return with return result; // return statement
}
}
// Displaying Values
namespacePraceticeConsoleApp
{
class program
{
static void Main (string[]args)
{
int result = GetValue.Calc(3,4); // Pass value and return result
Console.WriteLine(result); // View
}
}
}
For static, you do not need to instantiate with new
If you are studying the basics, I think it would be more difficult to use constructors instead of Static, so I will post it.
using System;
namespace experiment
{
class program
{
// Computational class
public class Calculate
{
// Class Fields
private int Value1;
private int Value 2;
// Addition Method
public int Addition() = > Value1 + Value2;
// substituted the fields in the class with argument constructor.
public Calculate (intval1, intval2)
{
Value1 = value1;
Value2 = value2;
}
}
static void Main (string[]args)
{
varcalc = new Calculate(1,2);
Console.WriteLine(calc.Addition());
Console.Read();
}
}
}
The Addition method uses the lambda expression, but another solution is the format below.
If the logic is just a single-line method, I think this is better for ease of viewing, so I adopted the lambda formula in the text.
public int Addition()
{
return Value 1 + Value 2;
}
© 2024 OneMinuteCode. All rights reserved.