How to make a function that subtracts a variable from another variable - c#

So I want to make a function that when it is called it subtracts a variable from another variable sorry if I am not being clear i want to do something like this
int TreeHealth = 100;
int HitValue = 25;
Hit();
{
TreeHealth - HitValue;
}
I tried doing that but it didn't work, so pls help.

You can make a function to return your value, for sample:
int Hit()
{
return TreeHealth - HitValue;
}
In this case, int is the result of the Hit function.
Using arguments
You also can pass arguments if you need:
int Hit(int tellHealth, int hitValue)
{
return tellHealth - hitValue;
}
The int type is the classic integer number, but there are other types you can work with math operations, such as decimal, double, short, long, etc.

public int Hit()
{
return TreeHealth - HitValue;
}

Related

Convert string to INT in C# (When String is 'E0305' To convert INT is not Work

I want to convert string to int but some time is not working.
Here is my code:
public static int ToInt(String pStr)
{
return Convert.ToInt32(Microsoft.VisualBasic.Conversion.Val(pStr));
}
Int i = ToInt("F0005");
Output is 0 - it works fine.
But when I pass in a value like this
Int i = ToInt("E0305");
Then I get an error "Out-of-range exception".
I have a mix of values, some are int and some are strings; I want to pass each and every value in loop and convert it to int, but when I pass this value then I get an error.
If you just want to skip invalid string value, it is better to use TryParse instead of returning 0 (which might be valid value). At your calling code it should look like this:
string val = "F0005";
if (int.TryParse(val, out int i) {
// parse success. you can use i here
}
else {
// parse failed.
}
If you really want it to be 0, this should work
string val = "F0005";
int i = int.TryParse(val, out int x) ? x : 0;
You can do it in C# alone without VB.NET library
public static int ToInt(string pStr)
{
return int.Parse(pstr);
}
Noted that this will throw exception if pStr is not a valid integer string. In your case, it might also throw exception if the value is too big, which you might need long instead to hold bigger numbers.
public static long ToInt64(string pStr)
{
return long.Parse(pstr);
}
Also, I just noticed that you are trying to parse "E0305" which is not really a valid format (as far as I know). The closest one is "1E305", which means 1 with 305 zeroes afterward. If you need to parse an integer that big, you might need BigInteger
public static BigInteger ToBigInteger(string pStr)
{
return BigInteger.Parse(pstr, System.Globalization.NumberStyles.AllowExponent);
}
The System.Globalization.NumberStyles.AllowExponent part is there to allow parsing the number in exponent representation.
Try using int.TryParse() method for those cases where you have some unexpected and you do not want exceptions in proces of parsing them.
Use case for it would be:
var isValid = int.TryParse(pStr, out int result);
Also another benefit of using it is that you have return value that provides you a way to handle unsuccessful parsing call.

How do I make a function not care about missing arguments in C# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can you use optional parameters in C#?
I am making text adventure, and using some code I found online, I have typewriter style printing. So I have this code in a function and besides passing in the code to type, I am also trying to pass in the delay between types. Now my problem is that I don't always want to have to put in the argument for the delay, I tried searching the default value of a int variable and seeing if making a if statement check if the variable was not its default and if it wasn't the default it would use what was passed in. Except it still won't work, it still wants me to pass in something. Is their anyway to get this to work?
Sorry if my question is confusing, I'm not the best at making non-confusing sentences... (see?)
You can use Optional Arguments:
public void MovePerson(int x, int y, int delay = 300)
{
}
Here, in this completely made up funciton, you can build in a default delay that will be set to 300 if you don't specify a value when calling the function.
MovePerson(10, 20); //Delay for 300
MovePerson(10, 20, 100); //Delay for 100
public void Task (String optional = "default") {
...
}
Just use default parameters
int Multiply (int a = 10, int b = 20)
{
return a * b;
}
Or you can also overload a function
int Multiply ()
{
return 10 * 20;
}
int Multiply (int a, int b)
{
return a * b;
}
The traditional method of addressing this issue is to have multiple method overloads. Here is one example:
public class Foo
{
public void Bar(string value)
{
Console.WriteLine(value);
}
public void Bar()
{
Bar("I have no value :(");
}
}
You can call Bar("hello world") or just Bar() and it will use a default value.
C# has since introduced syntactic sugar to make this easier, since it's such a common patter, by using optional arguments:
public void Bar(string value = "I have no value :(")
{
Console.WriteLine(value);
}
This will end up working in (approximately) the same way, but is much easier to type.

Pass on variable to set in C#

I want a pass several variables to a function to and set them to something else instead of reading from them. I am planning to use this in a scenario where i can create a object, and add it to a execution queue. Would a pointer be right for this?
I am aware my question has a poor explanation, but I don't know a better way to explain it.
It sounds like you probably want a ref or out parameter. For example:
public static void SetVariables(out int x, ref int y)
{
// Can't *read* from x at all before it's set
x = 10;
// Can read and write y
y++;
}
public static void Foo()
{
int setOnly;
int increment = 5;
SetVariables(out setOnly, ref increment);
Console.WriteLine("{0} {1}", setOnly, increment); // 10 6
}
See my parameter passing article for more information.
Are these variables reference types or value types? If they are reference types then you can pass them into your function as per normal and then mutate its properties from there. If they are value types then you must use the ref keyboard.

How to return value from function? (translate actionscript to c#)

So... I want to return value when C# function is called. I need a code example (simple summ of a,b values will be ok) Please help
I need something like this ( I know ActionScript so I will write in it):
public function sum(valueA:int, valueB:int):int
{
var summ:int = valueA + valueB;
return summ;
}
How to translate it into C#?
Here:
public int sum(int valueA, int valueB)
{
int summ = valueA + valueB;
return summ;
}
Differences to note:
The return type is declared immediately after the public visiblity qualifier
Variable types are declared before them
As a side-note, C# (3.0 above) also supports the var keyword when declaring variables, which means that you can write:
public int Sum(int valueA, int valueB) {
var summ = valueA + valueB;
return summ;
}
The meaning of var is porbably different than in ActionScript - it looks at the expression used to initialize the variable and uses the type of the expression (so the code is statically-typed). In the example above, the type of summ will be int just like in the version posted by Oded.
(This is often a confusing thing for people with background in dynamic languages, so I thought it would be useful to mention this, especially since var is also a keyword in ActionScript).
Or even so =)
public int Sum ( int valueA, int valueB ) { return valueA + valueB; }
if you don't need to store a result in a function for some purpose.

How to downcast a ref variable within the method

I need to downcast a long to an int in a method where the long is passed as a ref variable:
public void Foo(ref long l)
{
// need to consume l as an int
}
How can I easily do this?
You can't. However, any value you want to put into a ref int can be put into a ref long anyway - you've just got to worry about the initial value, and what you want to do if it's outside the range of int.
How many places do you need to write to the ref parameter or read it within your code? If it's only in one or two places, you should be okay just to cast appropriately at the right times. Otherwise, you might want to introduce a new method:
public void Foo(ref int x)
{
// Here's the body I *really* want
}
public void Foo(ref long x)
{
// But I'm forced to use this signature for whatever
// reasons. Oh well. This hack isn't an *exact* mimic
// of ref behaviour, but it's close.
// TODO: Decide an overflow policy
int tmp = (int) x;
Foo(ref tmp);
x = tmp;
}
The reason I say in the comments that it's not an exact mimic for the behaviour is that normally changes to the original ref parameter are visible even before the method returns, but now they'll only be visible at the very end. Also, if the method throws an exception, the value won't have been changed. The latter could be fixed with try/finally, but that's a bit clunky. In fact, if you want the try/finally behaviour you can do it all in a single method easily:
public void Foo(ref long x)
{
int y = (int) x;
try
{
// Main body of code
}
finally
{
x = y;
}
}
You don't. You can't take your reference and point it to a different type. How would the code calling your method know that it's changed?
If you just want to work with the value as an int, then you could do something like this:
private void Process(ref long l)
{
int i = (int)l;
// do whatever
}
You're a little light on the details, but if you're talking about this scenario:
public void Something(ref long something)
{
// code
}
int foo;
Something(ref foo);
try this:
long foo;
Something(ref foo);
int bar = (int) foo;
You can't safely cast a long to an int regardless of whether it's nullable or not as theres a chance it will overflow.
try this
if (!blah.HasValue)
blah = long.MaxValue;
int x = (int)blah.Value;
Console.WriteLine(x); //Not What you expect
You cannot directly cast this. The best option would be to cast it to a local, then assign it at the end of your method.
void Method(ref long myValue)
{
int tempValue = (int)myValue;
// change tempValue
myValue = tempValue;
}

Categories

Resources