Reputation: 2851
Im still kinda new to c# and there's something I cant quite get to grips with:
In VBA for example, if there is a bit of code I need throughout an app I would put it in a function then call it where ever I need it just by using the name of the function, eg
Sub Something()
If variable = x then
RunMyFunction
end if
End Sub
Is there a similar way of calling re-usable code in c#? I do realise its a completely different beast to what Ive worked with before
thanks
Upvotes: 1
Views: 127
Reputation: 1804
If your function do not return value use void:
private void FunctionName ()
{
// Do something...
}
If function return value than function have value type before function name:
private int FunctionNameReturnInt(int a, int b)
{
// Do something...
int res = a + b;
return num;
}
...
// Calling functions
FunctionName();
int res;
res = FunctionNameReturnInt(1,2);
`
Upvotes: 0
Reputation: 61725
Yes, I sometimes create a new class called CommonFunctions.cs
, and inside this class I would have the methods:
public class CommonFunctions
{
public static void Something(int Variable)
{
if(Variable == 5)
CommonFunctions.RunAnother();
}
public static void RunAnother()
{
}
}
Upvotes: 0
Reputation: 7390
Here is an example of a function:
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
if(result > 10)
{
return result;
}
}
You might find this article useful:
http://csharp.net-tutorials.com/basics/functions/
The biggest departure you'll need to make from VBA is that C# is truly object-oriented. You'll have to get used to the idea of functions being a member of a class that you have to instantiate (in most cases).
Upvotes: 0
Reputation: 66388
Yes C# comes with functions as well. Sub is actually a function with void
"return value".
So crude translation of your code to C# will be:
string RunMyFunction()
{
return "hello";
}
void Something(variable, x)
{
if (variable == x)
{
string value = RunMyFunction();
//.....
}
}
Upvotes: 2
Reputation: 41308
private void Something()
{
if (variable == x)
{
RunMyFunction();
}
}
private void RunMyFunction()
{
// does something
}
In other words - it is basically the same. You define your resuable function as a method (RunMyFunction above) and then call it by name (with parenthesis).
Upvotes: 2