I need help with C# programming; I am new to it and I come from C background. I have a Console Application like this:
using System;
using System.Collections
you have to make you're function static like this
namespace Add_Function
{
class Program
{
public static void(string[] args)
{
int a;
int b;
int c;
Console.WriteLine("Enter value of 'a':");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value of 'b':");
b = Convert.ToInt32(Console.ReadLine());
//why can't I not use it this way?
c = Add(a, b);
Console.WriteLine("a + b = {0}", c);
}
public static int Add(int x, int y)
{
int result = x + y;
return result;
}
}
}
you can do Program.Add instead of Add you also can make a new instance of Program by going like this
Program programinstance = new Program();
static void Main(string[] args)
{
Console.WriteLine("geef een leeftijd");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("geef een leeftijd");
int b = Convert.ToInt32(Console.ReadLine());
int einde = Sum(a, b);
Console.WriteLine(einde);
}
static int Sum(int x, int y)
{
int result = x + y;
return result;
}
You should either make your Add
function static
like so:
static public int Add(int x, int y)
{
int result = x + y;
return result;
} //END Add
static
means that the function is not class instance dependent. So you can call it without needing to create a class instance of Program
class.
or you should create in instance of your Program
class, and then call Add
on this instance. Like so:
Program prog = new Program();
prog.Add(5,10);
Because your function is an instance or non-static function you should create an object first.
Program p=new Program();
p.Add(1,1)
Note: in C# the term "function" is often replaced by the term "method". For the sake of this question there is no difference, so I'll just use the term "function".
Thats not true. you may read about (func type+ Lambda expressions),( anonymous function"using delegates type"),(action type +Lambda expressions ),(Predicate type+Lambda expressions). etc...etc... this will work.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int a;
int b;
int c;
Console.WriteLine("Enter value of 'a':");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value of 'b':");
b = Convert.ToInt32(Console.ReadLine());
Func<int, int, int> funcAdd = (x, y) => x + y;
c=funcAdd.Invoke(a, b);
Console.WriteLine(Convert.ToString(c));
}
}
}