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
Related
I made a method that have one parameter and iside it there is one member when i call this method in the main() and path a parameter to it with the ref keyword i recive error massage "argument 1 may not be passed with ref keword "
i tried to remove the ref keyworf it works well
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace learncsharp
{
class Program
{
static int Value(int x)
{
x = 100;
return x;
}
public static void Main()
{
int z = 10;
Value(ref z);
Console.Read();
}
}
}
i am expecting to get the sam result as to get 10
Parameters defined as 'ref' allow you to see changes from the caller after completion.
Parameters defined as 'out' MUST be set in the function, and their value after completion can be seen.
The declaration of 'ref' or 'out' must be in the function header AND the call to the function.
Otherwise parameters are passed by value, and any changes are lost.
Note that objects passed by value are sharing the same data on the heap, so any change to properties/fields of the object will also be seen by the caller as if they were passed by 'ref'
using your own code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace learncsharp
{
class Program
{
static int Value(ref int x)
{
x = 100;
return x;
}
public static void Main()
{
int z = 10;
Value(ref z);
Console.Read();
}
}
}
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.
I am trying to get a method of an object, and it works fine if the parameters of the method match the order of the list of parameters I provide. I am trying to avoid this, so I do not have to worry about the order of parameter types in methods across different files. Here is what I have
MethodInfo mi = stateType.GetMethod("Entrance", typesToUse.ToArray());
In my test case, typesToUse only contains two instances of unique interfaces,
IClass1 and IClass2 in that order.
If the Entrance method is : Entrance(IClass1 c1, IClass2 c2), it picks this method up. Although, if its Entrance(IClass2 c2, IClass1 c1), it will not and mi will then be null.
Is there a way around this? Perhaps a way to tell GetMethod to ignore parameter order?
Any help is appreciated and thank you.
It is not sensible to implement a method that will ignore parameter order. Parameter order is critical to determining that you have found the correct method.
Consider this simple class:
public class A
{
public void Foo(int a, string b)
{
PrintAString();
}
public void Foo(string b, int a)
{
FormatHardDrive();
}
}
If you're method ignored the parameter order...bad things might happen!
Having said all that, it is possible of course. Simply get all the methods with a given name, eliminate all those that do not contain parameters for all the types in typesToUse, and then ensure you only have one.
The following code demonstrates this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public class Program
{
public static void Main()
{
var typesToUse = new Type[] { typeof(int), typeof(string) };
var methods = typeof(A).GetMethods().Where(m => m.Name == "Foo");
var matchingMethods = methods.Where(m => ContainsAllParameters(m, typesToUse));
Console.WriteLine(matchingMethods.Single());
}
private static bool ContainsAllParameters(MethodInfo method, Type[] typesToUse)
{
var methodTypes = method.GetParameters().Select(p => p.ParameterType).ToList();
foreach(var typeToUse in typesToUse)
{
if (methodTypes.Contains(typeToUse))
{
methodTypes.Remove(typeToUse);
}
else
{
return false;
}
}
return !methodTypes.Any();
}
}
public class A
{
public void Foo(string a, int b)
{
Console.WriteLine("Hello World");
}
}
You could create an overload of the method, that takes the parameters in different order.
The recommended solution would probably just be to make sure they always are passed in the correct order.
If you can't ensure this, you might solve the problem by creating an overload of the method, or by performing some checks as the first thing in the Entrance-method.
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;
I am creating a really basic program, that has a method to fill an array but I am getting an error I don't understand. I am a Java programmer trying to acclimate to C# and .NET. Any help would be great.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
namespace TestThreads
{
class Program
{
static void Main(string[] args)
{
int[] empty = new int[50001];
int[] filled = new int[50001];
filled = compute(empty); //error occurs here
Console.ReadLine();
}
public int[] compute(int[] inArray)
{
for (int i = 0; i < inArray.Length; i++)
{
inArray[i] = i << 2;
}
return inArray;
}
}
}
Error Message:
Error 1 An object reference is required for the non-static field, method, or property 'TestThreads.Program.compute(int[])' C:\Users\hunter.mcmillen\Desktop\TestProcessSplitting\TestProcessSplitting\Program.cs 17 22 TestThreads
Thanks,
Hunter
The compute method should be static.
public static int[] compute(int[] inArray)
You're trying to call compute which is an instance method from Main which is a static method. To fix this make compute static as well`
public static int[] compute(int[] inArray)
Main is a static method - it is not specific to any single object - indeed, no instance of Program is created to call Main. compute is an instance method, and needs to be invoked on a single object.
Two options:
make compute static, which makes sense since it uses no state (fields):
public static int[] compute(int[] inArray) {...}
create an instance in Main:
var obj = new Program();
filled = obj.compute(empty);
The first is more appealing here. I've included the second purely for completeness.
Change public int[] compute(int[] inArray){...}
to
public static int[] compute(int[] inArray){..}
or change your call from
filled = compute(empty);
to
filled = new Program().compute(empty);
The compute() method that you have is an instance (non-static) method and requires an instance to be invoked.
Add static to the compute method declaration.
public static int[] compute(int[] inArray)
You're method is not static, but is being referenced from a static method. Change it to static. Solved.
public static int[] compute(int[] inArray) { ... }