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.Generic;
using System.Linq;
using System.Text;
namespace Add_Function
{
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());
//why can't I not use it this way?
c = Add(a, b);
Console.WriteLine("a + b = {0}", c);
}//END Main
public int Add(int x, int y)
{
int result = x + y;
return result;
}//END Add
}//END Program
}//END Add_Function
It gives me this error on the line that I call Add():
An object reference is required for the non-static field, method, or property 'Add_Function.Program.Add(int, int)'
Can anyone please explain to me why I have this problem. Is this because the architecture of C# is different than C, and the way I call it is wrong? Thanks.
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".
The other answers have already given you a quick way to fix your problem (just make Add a static function), but I'd like to explain why.
C# has a fundamentally different design paradigm than C. That paradigm is called object-oriented programming (OOP). Explaining all the differences between OOP and functional programming is beyond the scope of this question, but here's the short version as it applies to you.
Writing your program in C, you would have created a function that adds two numbers, and that function would exist independently and be callable from anywhere. In C# most functions don't exist independently; instead, they exist in the context of an object. In your example code, only an instance (an object) of the class Program knows how to perform Add. Said another way, you have to create an instance of Program, and then ask Program to perform an Add for you.
The solutions that people gave you, using the static keyword, route around that design. Using the static keyword is kind of like saying, "Hey, this function I'm defining doesn't need any context/state, it can just be called." Since your Add function is very simple, this makes sense. As you start diving deeper into OOP, you're going to find that your functions get more complicated and rely on knowing their state/context.
My advice: Pick up an OOP book and get ready to switch your brain from functional programming to OOP programming. You're in for a ride.
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);
This code gives you an error because your Add function needs to be static:
static public int Add(int x, int y)
In C# there is a distinction between functions that operate on instances (non-static) and functions that do not operate on instances (static). Instance functions can call other instance functions and static functions because they have an implicit reference to the instance. In contrast, static functions can call only static functions, or else they must explicitly provide an instance on which to call a non-static function.
Since public static void Main(string[] args) is static, all functions that it calls need to be static as well.
Because your function is an instance or non-static function you should create an object first.
Program p=new Program();
p.Add(1,1)
What that build error is telling you, that you have to either have an instance of Program or make Add static.
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));
}
}
}
Just make your Add function static by adding the static keyword like this:
public static int Add(int x, int y)
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();
The reason why you have the error is because your add function is defined after your using it in main if you were to create a function prototype before main up above it with public int Add(int x, int y); or you could just copy and paste your entire Add function above main cause main is where the compiler starts execution so doesn't it make sense to declare and define a function before you use it hope that helps. :D
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;
}
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;
Related
so basically I just started learning C# and yesterday I got the chance to learn about methods, I was a little bit confused about how are returns useful or what are they for, I know you can't have a return in a method that has void as part of the keyword and I know void means like "Don't do anything or don't return anything" something like that.
Well knowing that void means that.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
Add(2,2);
}
static int Add(int numberOne, int numberTwo)
{
Console.WriteLine(numberOne + numberTwo);
return numberOne + numberTwo;
}
}
}
How is the "return numberOne + numberTwo" useful in this code, I'm kinda stuck and I'm having a mental block why do I need the returns. when I run this code I get something (4)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Net;
namespace MethodsTutorial
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("I'm about to go into a method.");
DoSomethingAwesome();
Console.WriteLine("I'm back from the method.");
}
static void DoSomethingAwesome()
{
Console.WriteLine("I'm inside of a method, doing something awesome!");
}
}
}
And why in this code I also got something ("I'm inside of a method, doing something awesome!" ) and I don't use the keyword return at the end, I don't know if I'm explaining myself well enough ( sorry if I don't English is not my first language) but I just need a basic and well explanation on how are returns useful and what are they for and when to use them and when to not use them.
Thank you...
Calling the method:
DoSomethingAwesome();
In your main Program, results in writing the sentence:
"I'm inside of a method, doing something awesome!"
because the DoSomethingAwesome method prints this value to the console, even if it does not return any value (it's a void method).
The method performs this action, regardless of the fact that it does not return a value, simply because you called it. If you wanted to use its value, as a returned string, it should look like this:
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("I'm about to go into a method.");
string result = DoSomethingAwesome();
Console.WriteLine("I'm back from the method.");
}
static string DoSomethingAwesome()
{
return "I'm inside of a method, doing something awesome!";
}
}
The return type of a method declares what the caller should be expecting. When a method is declared with a void return type, it means that nothing gets returned from it, and therefore you don't need to use a return statement from void methods (because you aren't returning anything).
In the case below, you have:
static int Add(int numberOne, int numberTwo)
{
Console.WriteLine(numberOne + numberTwo);
return numberOne + numberTwo;
}
This means that the method Add returns an integer to whoever is calling it.
From your main function, you call:
Add(2,2);
This means you're calling the function, but you aren't doing anything with the result (just throwing it away). Instead, do:
int result = Add(2, 2);
The integer returned (4 in this case) is stored in result, so you can do:
Console.WriteLine("The method returned {0}", result);
Methods need a return to get data out of them.
In the case of int c = a + b, you can think of this like your method static int Add(int a, int b), which would be written as int c = Add(a, b)
In order to get the new value out of the method, the method needs to be able to return a value to the caller, which in this case then gets assigned to c.
The whole point of methods is to separate out frequently used portions of code, or to split large chunks of code into smaller, easier to understand chunks.
I'd suggest having a look at the Documentation.
The question here is quite basic and isnt only related to C#, infact almost every programming language uses return in methods.
Basically return indicates you wish to exit the method execution. Now when you have a void method, which is a method that does not return a value from the execution. Other than a void a method can return any type that is required.
Here is a basic example void method.
class Program
{
static void Main()
{
Calculate(1 , 2);
}
static int c = 0;
static void Calculate(int a, int b)
{
c = a + b;
}
}
Now in my Calculate method I am setting the value of my field c to the sum of a + b. This is basic, however the void method is not returning a value but modifying a value (c).
Now this could be written as:
class Program
{
static void Main()
{
c = Calculate(1 , 2);
}
static int c = 0;
static int Calculate(int a, int b)
{
return a + b;
}
}
Where will notice my Calculate method is now returning an int which is the sum of a + b. This is being assigned to c from the calling method.
Now why use either case. Well in the first example the method Calculate() knew which variable should hold the result of the method. Therefore it set c to the sum. In the second example the Calculate method simply returns the sum of a + b.
Now moving on to a more complex example. Lets say we build a calculator class whos responsibility is the manage the calculation.
class Calculator
{
int sum = 0;
public void Add(int a)
{
sum += a;
}
public void Subtract(int a)
{
sum -= a;
}
public int GetTotal()
{
return sum;
}
}
Which could be used as:
static void Main()
{
var calculator = new Calculator();
calculator.Add(5);
calculator.Subtract(10);
int total = calculator.GetTotal();
}
Again basic but now we have 3 methods. Add, Subtract and GetTotal. Both Add and Subtract are void methods as they are performing operations on the sum field. Where the GetTotal is returning the sum.
Hope this helps a bit.
Is it possible to pass a function (like let's say sin() ) via string and then use it as int?
Like: (main idea only)
public int getfunc(String func)
{
return res_of(func)
}
I tried playing around with string of "Math.sin(0)"
but couldn't print the 0...
I could predefine the math functions since I only need 1 and then it becomes extremely simple as I only pass the int value for the function to work on, but I thought may-hap there is a way to keep it more generic.
I do not want to use mapping of the functions I want to keep it dynamic....
is ther a way of doing so?
I'd like to offer an alternative approach that you may not have considered.
You could use a delegate instead of passing a string; that way, you won't need any reflection.
There's a predefined delegate type in C# called Func<> which lets you easily define the return type and parameter types of a method that you want to pass as a delegate.
For example, the Func<> for Math.Sin(double) would be Func<double, double> because Math.Sin() returns a double and takes a double parameter.
An example will make this clearer:
using System;
namespace Demo
{
internal class Program
{
private void run()
{
Func<double, double> f1 = Math.Sin;
Func<double, double> f2 = Math.Cos;
double r1 = runFunc(f1, 1.0);
double r2 = runFunc(f2, 2.0);
Console.WriteLine(r1);
Console.WriteLine(r2);
}
private static double runFunc(Func<double, double> func, double parameter)
{
return func(parameter);
}
private static void Main()
{
new Program().run();
}
}
}
Try using http://www.csscript.net/
dynamic script = CSScript.Evaluator
.LoadCode(#"using System;
public class Script
{
public int Sum(int a, int b)
{
return a+b;
}
}");
int result = script.Sum(1, 2);
Declare the method like this:
public int DoCalculation(Func<double, double> func, double a)
{
return Convert.ToInt32(func(a));
}
Then use it like this:
int result = DoCalculation(Math.Sin, 3.3);
In our application we use the .NET integrated C# compiler.
This is some work to do but straight-forward to implement.
Here's an answer with a lot more details on that.
We use this in our companies production.
Hello I have the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace myConsole
{
public delegate int showDelegate();
public class addmultipleClass
{
public int addNumbers(int a, int b)
{
return (a + b);
}
public int multiplyNumbers(int a, int b)
{
return (a * b);
}
}
class Delegate
{
static void Main(string[] args)
{
addmultipleClass myObj = new addmultipleClass();
showDelegate add = new showDelegate(myObj.addNumbers);
}
}
}
It is showing error like this No overload for 'addNumbers' matches delegate 'myConsole.showDelegate'
Why it is showing this error. Whats wrong in my code. Is it not correct way to reference the addNumbers() method.
Why should i use the delegate over here. I can achieve this by using class object. as myObj.addNumbers(10,20);
So what is the need for delegate?
Please help me.
Thank you all.
Modify showDelegate to match the parameters of addNumbers:
public delegate int showDelegate(int a, int b);
Delegates have to match the number and type of parameters in addition to your return type.
The second part of your question is essentially asking: "why delegates?". For that answer, I suggest you look at other Stack Overflow posts for much more detailed and precise answers, for a start:
Delegates, Why?
when & why to use delegates?
The purpose of delegates
I'm building a system a bit like LINQ, and in doing it, am trying to support polymorphic callback handler lists, and am running into several kinds of problems. The short way to ask my question is to just show you some code. My new system supports "Groups" and groups have a vector of entry points (below, UPDATE and CHECKPT) and each element on the vector is a polymorphic list of delegates, which I'll call back using reflection.
So, sample code:
namespace ConsoleApplication1
{
internal delegate void GroupISDHandler(int i, string s, double d);
class Group
{
public class myHandlers {
internal List<Delegate> hList = new List<Delegate>();
public static myHandlers operator +(myHandlers a, Delegate b) {
a.hList.Add(b);
return a;
}
}
public class mimicVector {
public List<myHandlers> ListofhLists = new List<myHandlers>();
public myHandlers this[int i] { get { return ListofhLists[i]; } set { ListofhLists[i] = value; } }
}
public mimicVector handlers = new mimicVector();
public Group(string name) { ... }
}
class Program
{
internal const int UPDATE = 0;
internal const int CHECKPT = 1;
public static void Main()
{
Group g = new Group("group name");
g.handlers[UPDATE] += (GroupISDHandler)delegate(int x, string s, double d) {
Console.WriteLine("my int,string,double handler was called, with x = {0}, s = {1}, d = {2}",
x,s,d);
};
}
}
}
My questions centers on the registration line. Why can't C# infer the types so that I could omit the cast and the new delegate type entirely? I would think that from
g.handlers[UPDATE] += delegate(int x, string s, double d) {
Console.WriteLine(....);
};
C# could infer the needed type signature. delegate() would be a kind of anonymous type and C# would just generate something like
private delegate void _atype1(int _a0, string _a1, double _a2)
and then insert (Delegate)(_atype1) before compiling the line. Thus my user won't need to declare a delegate type (which currently forces her to type the argument list twice, in effect).
I do have System.Linq since I'm on VS 2010. So if LINQ can somehow infer the needed casts...
you should be able to do it this way:
g.handlers[UPDATE] += (GroupISDHandler)((x, s, d) =>
Console.WriteLine(
"my int,string,double handler was called, with x = {0}, s = {1}, d = {2}",
x, s, d));
another option would be:
have a class named ´Parameters´ that is a container for whatever the user can send, might be defined types if they never change, or a list of objects if you pretend to send and receive different amount of parameters. Then instead of a Delegate, you would take Action that equals a delegate that takes one argument, and you could do your call without casting like this:
p => Console.WriteLine("x = {0}, s = {1}, d = {2}", p.x, p.s, p.d);
Turns out that the answer is basically this: while you can do the inference in the kinds of situations I had in mind, the C# owners want completely general solutions and polymorphism makes the type inference problem too hard to solve in a sufficiently general way, in their view. I myself disagree since I end up typing all my type signatures twice, but that's their reasoning.
If I have a method for calculating the greatest common divisor of two integers as:
public static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
What would be the best way to attach that to the System.Math class?
Here are the three ways I have come up with:
public static int GCD(this int a, int b)
{
return b == 0 ? a : b.GCD(a % b);
}
// Lame...
var gcd = a.GCD(b);
and:
public static class RationalMath
{
public static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
}
// Lame...
var gcd = RationalMath.GCD(a, b);
and:
public static int GCD(this Type math, int a, int b)
{
return b == 0 ? a : typeof(Math).GCD(b, a % b);
}
// Neat?
var gcd = typeof(Math).GCD(a, b);
The desired syntax is Math.GCD since that is the standard for all mathematical functions.
Any suggestions? What should I do to get the desired syntax?
You cannot. Extension methods are just syntactic sugar for calling a static function and passing an instance of a particular type. Given that, they operate only on instances, as they must be defined by passing a this parameter of the type you want to attach to.
I would prefer the one with RationalMath. You really don't need extension methods here, because their aim is to mimic instance methods of objects of you can't modify. But here one should use plain old static method.
Given the fact that you cannot extend the static Math class I would go for sample #2. It follows the pattern used by Math, does not clutter the int method space, and is simple and clean to invoke. #3 is plain horrible :)
Personally, I wouldn't do it the way you want. System.Math is just one static class that contains some mathematical functions . . . there's no reason it has to contain every mathematical function you'd ever want to use.
However, if you really want this, I suppose you could write your own static Math class that's a sort of wrapper for System.Math . . . basically just implement every function in System.Math by passing it along to the actual System.Math class. Like this:
public static class Math
{
public static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
// Implement the System.Math methods
public static double Pow(double x, double y)
{
return System.Math.Pow(x, y);
}
// etc.
}
This seems like a real pain in the neck though for not much benefit. (Kind of an anti-syntactic sugar.) But it would let you call Math.GCD(a,b) and, say, Math.Pow(x,y) from the same class, which is what it sounds like you want.
Ok, one other way I thought of:
namespace My
{
public static class Math
{
}
}
namespace MainApp
{
...
var gcd = My.Math.GCD(a, b);
...
}