Cannot convert from method group to Int32 - c#

I want my small math program to look really sleek, and by this I mean under the Main method I have the following methods:
Greet()
UserInput1()
UserInput2()
Result()
In Greet() I just say "HI", in UserInput1() I want to collect the first number, in UserInput2() I want to collect the second number, and in Result() I want to print the result of UserInput1 + UserInput2. I can collect the number in UserInput 1 and 2 but I can’t seem to send them to Result() without assigning values to them under the Main() function.
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Greet();
firstNumber();
secondNumber();
result(firstNumber, secondNumber);
Console.ReadKey();
}
public static void Greet()
{
Console.WriteLine("Hello, pls insert two numbers");
}
public static int firstNumber()
{
int num01 = Convert.ToInt32(Console.ReadLine());
return num01;
}
public static int secondNumber()
{
int num02 = Convert.ToInt32(Console.ReadLine());
return num02;
}
public static void result( int num01, int num02)
{
Console.WriteLine(num01 + num02);
}
}
}

change this:
result(firstNumber, secondNumber);
to this:
result(firstNumber(), secondNumber());
and remove the calls to the 2 methods in the two lines above.
To call a method without parameters, you need the parentheses without content.

Cannot convert from method group to int
This error message occurs when you attempt to take a method (without invocation) and pass it as a type. The result method is expecting two parameters of type int, but you're attempting to pass it the method, rather than the result of the method invocation.
You need to store the results in a variable, or invoke the methods with the ():
Like this:
static void Main(string[] args)
{
Greet();
var first = firstNumber();
var second = secondNumber();
result(first , second );
Console.ReadKey();
}
or this:
static void Main(string[] args)
{
Greet();
result(firstNumber(), secondNumber());
Console.ReadKey();
}

Call the method like the following, So that the method result will be called with output from the firstNumber() and secondNumber() as well :
result(firstNumber(),secondNumber());
Few more suggestions:
Make the method Greet() to a re-usable one by passing appropriate message and then display it. so that you can use the same for all display operations. the signature of the method will be:
public static void Greet(string message)
{
Console.WriteLine(message);
}
The method Convert.ToInt32() will convert the given input to an integer value only if the input is convertible. else it will throws FormatException. So i prefer you to use int.TryParse for this purpose. Which will help you to determine whether the conversion is success or not. so the Method signature for firstNumber() will be like the following:
public static int firstNumber()
{
int num01=0;
if(!int.TryParse(Console.ReadLine(),out num01))
{
Greet("Invalid input");
}
return num01;
}
Hope that you will change the secondNumber() as well

Related

Performing actions with method returned values

I have class: class_getanswer and class: class_performaction
in class_getanswer i have method:
class class_getanswer
{
static public int capacity()
{
Random block = new Random();
int beta = block.Next(1, 8);
return beta;
}
}
in class with method Main i want that answer to be in function if:
class class_performaction
{
static void Main()
{
int value = 5;
if(class_getanswer.capacity() < value)
{
Console.WriteLine("bla bla bla");
}
}
}
but i get that "if" doesn't exist in this context, why?
There is screenshot of kinda full programm but in different language (lithuanian): https://www.dropbox.com/s/jggwgt738vltawx/functionswt.PNG?dl=0
Please check the case of, if statement. I believe you wrote If(with a capital 'I'), change it to small case 'i'.

String class behavior

public void main()
{
string test = "testing";
ChangeVal(test);
Console.WriteLine(test);
}
private void ChangeVal(string test)
{
test = "in child";
}
If String is a class.
and i pass string as a parameter to a function. change the value of that string in function.
But in main function it shows the previous values. It will print testing value.
when i created Foo class which has 2 member variable integer and string.
when i passed the object of the class as parameter and change value of the member variable in function.
It will give updated value in the main function
public class Foo
{
public string test = "testing";
public int i = 5;
}
public void main()
{
Foo obj=new Foo();
Console.WriteLine(obj.test);
ChangeVal(obj);
Console.WriteLine(obj.test);
}
private void ChangeVal(Foo obj)
{
obj.test = "in child";
obj.i = 5;
}
If string is the class. It will update the value of the variable.
May string is the sequence of Unicode character that's why it doesn't update the value in 1st case.
Can any body will explain this in detail.
change the value of that string in function
Strings are immutable. You can't change the value of a string. You can assign another string to the same reference, but you would need to pass the reference in by using ref.
public void main()
{
string test = "testing";
ChangeVal(ref test);
Console.WriteLine(test);
}
private void ChangeVal(ref string test)
{
test = "in child";
}
You Foo class, however, is mutable, so you can assign different values to its members.
Try to pass the parameter by reference to get the var updated in main thread:
private void SeString(ref string chain)
{
chain="new string";
}
Then call:
string variable="hello";
SeString(ref variable);
string output is "new string"

Delegate.DynamicInvoke

I want to invoke the method by the method name stored in the list. Can anyone help? I'm new to c#!
{
delegate string ConvertsIntToString(int i);
}
class Program
{
public static List<String> states = new List<string>() { "dfd","HiThere"};
static void Main(string[] args)
{
ConvertsIntToString someMethod = new ConvertsIntToString(states[1]);
string message = someMethod(5);
Console.WriteLine(message);
Console.ReadKey();
}
private static string HiThere(int i)
{
return "Hi there! #" + (i * 100);
}
}
It looks like you don't need Delegate.DynamicInvoke at all - you're not trying to invoke it dynamically - you're trying to create the delegate dynamically, which you can do with Delegate.CreateDelegate. Short but complete program based around your example (but without using a list - there's no need for that here):
using System;
using System.Reflection;
delegate string ConvertsIntToString(int i);
class Program
{
static void Main(string[] args)
{
// Obviously this can come from elsewhere
string name = "HiThere";
var method = typeof(Program).GetMethod(name,
BindingFlags.Static |
BindingFlags.NonPublic);
var del = (ConvertsIntToString) Delegate.CreateDelegate
(typeof(ConvertsIntToString), method);
string result = del(5);
Console.WriteLine(result);
}
private static string HiThere(int i)
{
return "Hi there! #" + (i * 100);
}
}
Obviously you need to adjust it if the method you want is in a different type, or is an instance method, or is public.

How to pass method result as parameter to base class constructor in C#?

I've trying to achieve something like this:
class App {
static void Main(string[] args) {
System.Console.WriteLine(new Test("abc")); //output: 'abc'
System.Console.ReadLine();
}
}
I can do this passing by an variable:
class Test {
public static string str;
public Test (string input) { str = input; }
public override string ToString() {
return str;
}
}
works fine.
But, my desire is do something as:
class Test {
public static string input;
public Test (out input) { }
public override string ToString() {
return input;
}
}
System.Console.WriteLine(new Test("abc test")); //abc test
Don't works.
How I do this?
Thanks,advanced.
You can't. The variable approach is exactly the correct way, although the variable shouldn't be declared static, and shouldn't be a public field.
class Test {
public string Input {get;set;}
public Test (string input) { Input = input; }
public override string ToString() {
return Input;
}
}
I have an impression that you're not entirely understand what out keyword means. Essentially when you're writing something like void MyMethod(out string var) it means you want to return some value from method, not pass it into method.
For example there's bool Int32.TryParse(string s, out int result). It parses string s, returns if parse was successful and places parsed number to result. Thus, to correctly use out you should have real variable at the calling place. So you can't write Int32.Parse("10", 0) because this method can't assign result of 10 to 0. It needs real variable, like that:
int result;
bool success = Int32.TryParse("10", out result);
So, your desire is somewhat else - it is not in line with language designer's intentions for out :)

Error CS1001 (Identifier expected)

I'm new to programming and am taking a C# class. I am getting compiler error CS1001 when I try to write this program.
I read the Compiler Error description (link below), but I'm really not getting it. What am I doing wrong?
http://msdn.microsoft.com/en-us/library/b839hwk4.aspx
Here is my source code:
using System;
public class InputMethodDemoTwo
{
public static void Main()
{
int first, second;
InputMethod(out first, out second);
Console.WriteLine("After InputMethod first is {0}", first);
Console.WriteLine("and second is {0}", second);
}
public static void InputMethod(out first, out second)
// The error is citing the line above this note.
{
one = DataEntry("first");
two = DataEntry("second");
}
public static void DataEntry(out int one, out int two)
{
string s1, s2;
Console.Write("Enter first integer ");
s1 = Console.ReadLine();
Console.Write("Enter second integer ");
s2 = Console.ReadLine();
one = Convert.ToInt32(s1);
two = Convert.ToInt32(s2);
}
}
According to the instructions, I'm supposed to have a method b (InputData) which pulls statements from method c (DataEntry)... Here are the instructions:
The InputMethod()in the InputMethodDemo program in Figure 6-24 contains repetitive
code that prompts the user and retrieves integer values. Rewrite the program so the
InputMethod()calls another method to do the work. The rewritten InputMethod()
will need to contain only two statements:
one = DataEntry("first");
two = DataEntry("second");
Save the new program as InputMethodDemo2.cs."
The InputMethodDemo they are referring to is the same program, except that it calls only one method (the InputMethod) instead of two.
The text I referred to above is "Microsoft® Visual C#® 2008, An Introduction to Object-Oriented Programming, 3e, Joyce Farrell"
Any advice/ help would be greatly appreciated.
This is what you are expected to do:
using System;
public class InputMethodDemoTwo
{
public static void Main()
{
int first, second;
InputMethod(out first, out second);
Console.WriteLine("After InputMethod first is {0}", first);
Console.WriteLine("and second is {0}", second);
Console.ReadLine();
}
public static void InputMethod(out int first, out int second)
//Data type was missing here
{
first = DataEntry("first");
second = DataEntry("second");
}
public static int DataEntry(string method)
//Parameter to DataEntry should be string
{
int result = 0;
if (method.Equals("first"))
{
Console.Write("Enter first integer ");
Int32.TryParse(Console.ReadLine(), out result);
}
else if (method.Equals("second"))
{
Console.Write("Enter second integer ");
Int32.TryParse(Console.ReadLine(), out result);
}
return result;
}
}
Change
public static void InputMethod(out first, out second)
{
one = DataEntry("first");
two = DataEntry("second");
}
to
public static void InputMethod(out DataEntry first, out DataEntry second)
{
first = DataEntry("first");
second = DataEntry("second");
}
You haven't provided the type of the arguments. Also, your arguments are called first and second, not one and two.

Categories

Resources