c# passing Parameters values from function to other function - c#

are there any way to get the values from Parameters in "functionone" and calculate it in the "functiontwo" without writing that again that's a small code for example what i mean
public void functionone(int x, int y)
{
x = 1;
y = 2;
}
public void functiontwo(int a , int b )
{
a=x+y;
b=x-y;
Console.WriteLine(a);
Console.WriteLine(b);
}

You are implementing functionone wrongly I guess
doing this:
public void functionone(int x, int y)
{
x = 1;
y = 2;
}
is normally not the way to pass parameters and change its values in the method,
or saying in another way, x and y should be holding the values you pass as parameters, and no getting assigned inside the method..
define a global x and global y, then you can access to it everywhere in that scope..
Example:
class Abc{
int globalX;
int globalY;
....
public void functionone(int x, int y)
{
globalX = 1 + x;
globalY = 2 + y;
}
public void functiontwo(int a , int b )
{
a=globalX + globalY;
b=globalX - globalY;
Console.WriteLine(a);
Console.WriteLine(b);
}
}

To explain my comment:
int globalX;
int globalY;
public void functionone(ref int x, ref int y)
{
x = 1;
y = 2;
}
public void functiontwo(ref int a , ref int b)
{
a = globalX + globalY;
b = globalX - globalY;
Console.WriteLine(a);
Console.WriteLine(b);
}
// in main
functionone(ref globalX, ref globalY);
// globalX and globalY are now 1 and 2
functiontwo(ref a, ref b);
// a = 3 and b = -1 -> 'globalX +/- globalY'
This way you can set the values of any variables you pass to functionone or functiontwo.
However it doesn't look good and in my opinion it's not a good code. Your concept seems wrong, so maybe you can post a description of the problem you encountered?

Related

Beginner question about a task in a course in C#

The code
class Program
{
static int Add(int x, int y)
{
x = 4;
y = 3;
int f = x + y;
return f;
}
static void Main(string[] args)
{
int x = 4;
int y = 3;
Console.WriteLine("Answer: ");
Add(x, y);
}
}
Doing a beginner course in C# and I have been stuck at this question for two days now.
I know its probably really simple, but I have tried so many different things that I think I have made it harder for me than it really.
I fixed to call strings in methods, but numbers seems hard.
The task is about to take two numbers in and that return the answer.
Tried searching around all the different errors I got with all the different tries, but didn't find the help, or the answers I understand.
You almost did all of it, just with 2 issues.
You should relay on the numbers you pass from Main to Add and not reassign the values inside Add otherwise passing them is useless and unusable for other numbers.
Add returns a value but you never save it + print it.
Example for #1
static int Add(int x, int y)
{
int f = x + y;
return f;
}
Example of #2
var result = Add(x, y);
Console.WriteLine(result);
Corrected Example:
class Program
{
static int Add(int x, int y)
{
// You don't need to redefine the variables x and y,
// because you get them when you call the method
// You can shorten the last part
// and just return the Addition
return x + y;
}
static void Main(string[] args)
{
int x = 4;
int y = 3;
// Prints the Word Answer
// as well as the Addition result into the Console now
Console.WriteLine("Answer: " + Add(x, y));
}
}
Your Errors:
You never printed the Result into the Console!
You shouldn't redefine the variables in the Function, because if you do that you don't need to use a function in the first place
You can shorten the return statement (you don't have to)
You can add Add(x,y) into the Console.WriteLine because it returns a Integer, therefore it is basically like writting Console.WriteLine("Answer: " + 7);
Here is an working version with explaination:
class Program
{
static int Add(int x, int y)
{
//x = 4; these are passed in as parameter, no need to set it
//y = 3;
int f = x + y;
return f;
}
static void Main(string[] args)
{
int someX = 4; //these are only known inside the scope of "Main"
int someY = 3;
int result = Add(someX, someY); //these are passed inside the function,
//the value is copied
Console.WriteLine("Answer: " + result.ToString());
}
}
You can do it even easier and simple In addition , this answer is more dynamic as you can choose the two numbers every time you run the program:
class Program
{
static int Add(int x, int y)
{
return x + y;
}
static void Main(string[] args)
{
Console.WriteLine("Answer: " + Add(Convert.ToInt32(Console.ReadLine()),
Convert.ToInt32(Console.ReadLine())).ToString());
Console.ReadLine(); //In order to be able to see the result in the screen
}
}

Get name of delegate method

Out of curiosity I've been looking into delegate methods and am interested in getting the name of the current delegate method that is being used (just for fun, really).
The code I have is as follows (with the current/desired outputs):
private delegate int mathDelegate(int x, int y);
public static void Main()
{
mathDelegate add = (x,y) => x + y;
mathDelegate subtract = (x,y) => x - y;
mathDelegate multiply = (x,y) => x * y;
var functions = new mathDelegate[]{add, subtract, multiply};
foreach (var function in functions){
var x = 6;
var y = 3;
Console.WriteLine(String.Format("{0}({1},{2}) = {3}", function.Method.Name, x, y, function(x, y)));
}
}
/// Output is:
// <Main>b__0(6,3) = 9
// <Main>b__1(6,3) = 3
// <Main>b__2(6,3) = 18
/// Desired output
// add(6,3) = 9
// subtract(6,3) = 3
// multiply(6,3) = 18
Does anyone know of any way(s) I could achieve this? Thanks.
Your methods are anonymous delegates, so the the compiler gives each of them a name that doesn't have any meaningful connection back to the variable name. If you want them to have better names then make them actual methods:
public int Add(int x, int y)
{
return x + y ;
}
etc. Then reference them by name:
var functions = new mathDelegate[]{this.Add, this.Subtract, this.Multiply};
Note that the this. is optional but illustrates that they are class members rather than local variables.

multiple out parameters with a return

I have a method declaration like this:
public int myMethod(int x, out int y, out int z)
{
int k;
foreach(int i in someList)
{
if(anotherMethod(out k))
{
z = k;
}
else
{
z = 0;
}
}
y = someValue;
return anotherValue;
}
but I get this compiling error
The out parameter 'z' must be assigned to before control leaves the current method
If someList is empty, it will never enter the foreach loop, and therefore z will never be assigned. To resolve this, ensure that z is given a value regardless of of the contents of someList:
public int myMethod(int x, out int y, out int z)
{
z = 0; // or whatever default value you like
...
}
However, you should probably consider refactoring this code. It's likely there's a better way to accomplish this. If you'd really like to return 3 different int values, you might consider using a Tuple<int, int, int> or creating a custom data type to represent the value.
Reason : out paramaeters must be initialised before returning from the function.
You are assigning value for parameter z inside if block so compiler
could not identify whether it can be initialized or not hence initialize
your parameter z before if block as below:
public int myMethod(int x, out int y, out int z)
{
int k;
z=0;
foreach(int i in someList)
{
if(anotherMethod(out k))
{
z = k;
}
else
{
z = 0;
}
}
y = someValue;
return anotherValue;
}
If someList is empty, then z will never be assigned a value, which violates it's being an out variable. Remove the out constraint, or reconfigure your function logic.

C# Methods: Defined Parameter Default Value Issue

I am writing an app that requires the calculation of the Gamma function.
A code (part of a class) snippet is below:
namespace PB.Utilities.Math
{
// class definition
public class SpecialFunctions
{
// Private Fields
// Instance Constructor
public SpecialFunctions() {}
// Public Method for Gamma Function
// x = input value; x MUST BE > 0
// GammaLn = secondary output value equal to natural log of Gamma Function
public double Gamma(double x, out double GammaLn)
{
try
{
if (x <= 0) throw new System.ArgumentException("arg <= 0 in GammaFunction", "x");
}
catch
{
System.Console.WriteLine("argument <= 0 in GammaFunction");
System.Console.ReadKey();
}
double gammaln;
double _gamma = gamma(x, out gammaln);
GammaLn = gammaln;
return _gamma;
}
// private method for Gamma Function
private double gamma(double xx, out double gammaln)
{
// private constants
int j;
double x,tmp,y,ser;
const double k1 = 5.24218750000000000;
const double k2 = 0.999999999999997092;
const double k3 = 2.5066282746310005;
double[] cof = new double[14]
{
57.1562356658629235, -59.5979603554754912, 14.1360979747417471,
-0.491913816097620199, 0.339946499848118887e-4, 0.465236289270485756e-4,
-0.983744753048795646e-4, 0.158088703224912494e-3, -0.210264441724104883e-3,
0.217439618115212643e-3, -0.164318106536763890e-3, 0.844182239838527433e-4,
-0.261908384015814087e-4, 0.368991826595316234e-5
};
y = x = xx;
tmp = x + k1;
tmp = (x + 0.5) * System.Math.Log(tmp) - tmp;
ser = k2;
for (j = 0; j < 14; j++) ser += cof[j]/++y;
gammaln = tmp + System.Math.Log(k3*ser/x);
return System.Math.Exp(gammaln);
}
}
}
public class BSA
{
static void Main()
{
// Create an object of type PB.Utilities.Math.SpecialFunctions
PB.Utilities.Math.SpecialFunctions Function = new PB.Utilities.Math.SpecialFunctions();
// Call the public method GammaFunction.
double GammaLn1;
double GammaLn2;
double GammaLn3;
double g1 = Function.Gamma(3.5, out GammaLn1);
double g2 = Function.Gamma(1.5, out GammaLn2);
double g3 = Function.Gamma(1/7, out GammaLn3);
System.Console.WriteLine("g(7/2) = "+g1);
System.Console.WriteLine("g(3/2) = "+g2);
System.Console.WriteLine("g(1/7) = "+g3);
}
}
The issue is that at compilation, the parameter x in Gamma (even though x is being assigned the value 3.5 in the calling component) is assigned a value of 0 which triggers the exception. Can anyone please suggest how I can get around this? Thank you.
Seems to be 3.5 in my test cases. Are you sure you haven't excluded some information that might be the issue?
using System;
namespace Doubletesting
{
class Program
{
static void Main(string[] args)
{
double d = Doubletesting.TestDouble(3.5);
Console.WriteLine(d.ToString());
Console.ReadKey();
}
public static double TestDouble(double x)
{
double result;
result = x;
return result;
}
}
}
Result
3.5
UPDATED
The Error is caused by your Function.Gamma(1 / 7, out GammaLn3). This is because both 1 and 7 are INT and dividing (int)1 by (int)7 is zero. Try Function.Gamma(1f / 7f, out GammaLn3).

Is swap method in C# whose parameters have value type not efficient?

Check this method:
public static void Swap(ref int i, ref int j)
{
int aux=i;
i=j;
j=aux;
}
Is it more efficient than this?
public static void Swap1(int[] a, int i, int j)
{
int aux=a[i];
a[i]= a[j];
a[j]=aux;
}
I'm using these methods like this:
static void Main(string[] args)
{
int[] a = { 5, 4, 3, 1 };
Swap(a[1], a[2]);
Swap(a, 1, 2);
}
Which of these methods is more efficient and why?
Your method will not swap any parameters at all. I mean it will swap parameters inside your method, but it will not affect the values of source parameters. That's because value types are copied when they are passed into methods. Here's the example:
void IncorrectSwap(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
void HereHappensNothing()
{
int a = 1;
int b = 2;
IncorrectSwap(a, b);
// a still = 1, and b = 2, nothing happens
}
To make your method work you have to pass value types by reference like that:
void CorrectSwap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
void HereSwapHappens()
{
int a = 1;
int b = 2;
CorrectSwap(ref a,ref b);
// a = 2, and b = 1, Ok.
}
Here you can read about value types and how to work with them.
Update
Following your update. I don't think there should be any significant difference in performance as long as value types don't get boxed when passed by ref. There can be some penalty when you pass more parameters, but I don't think it should be significant, you will not see the difference.
Not passing by ref will not work. As you will only be affecting the local parameters.
Your code does nothing!
When parameters are passed by value you can't change them.
So to correctly implement Swap you need to pass by ref.

Categories

Resources