I am having some trouble with visual studio, as it says it won't compile. I can't figure out what the problem is. it says something like it can't convert from void to bool, even though there is no 'bool'. Here is my code:
using System;
namespace ConsoleApplication14
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(myFunction(14));
}
public static void myFunction(int x)
{
return x + 2;
}
}
What is causing that compile error?
try this
class Program
{
static void Main(string[] args)
{
Console.WriteLine(myFunction(14));
}
public static int myFunction(int x)
{
return x + 2;
}
}
You are returning an Int. Void has no return type. To make this work you will need
public static int myFunction(int x)
{
return x + 2;
}
The type void indicates that a mamber does not return anything. So when your method is marked as such it should not return a value. However when you call Console.WriteLine you need a value to be printed to the console.
Furthermore your method should make a calculation and return something - in your case an int. So instead of defining your method as void let it return an int:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(myFunction(14));
}
public static int myFunction(int x)
{
return x + 2;
}
}
In your myfunction method your returning some int value but myfunction return type is void in your code. Plaese change void to int and the application will work.
namespace ConsoleApplication1
{
class Program
{
public static int myFunction(int x)
{
return x + 2;
}
static void Main(string[] args)
{
Console.WriteLine(myFunction(14));
Console.ReadLine();
}
}
}
Related
I am a beginner in C# and was creating a program with functions but unfortunately am very confused how to return the value in the function to the main program.
I have researched for other similar questions but i cannot find the answer as it is very basic.
class Program
{
public int answer = 0;
public int column = 0;
public int UserInput;
static void Main(string[] args)
{
BinaryInput(int UserInput);
Console.WriteLine(UserInput);
}
static int BinaryInput (ref int UserInput)
{
UserInput = int.Parse(Console.ReadLine());
return UserInput;
}
}
}
Using a return value and a ref parameter at the same time for the same thing is completely unnecessary.
Just choose a method like this:
static int GetBinaryInput()
{
return int.Parse(Console.ReadLine());
}
static void Main(string[] args)
{
int UserInput = GetBinaryInput();
Console.WriteLine(UserInput);
}
Or like that, prefering out here:
static void GetBinaryInput(out int UserInput)
{
UserInput = int.Parse(Console.ReadLine());
}
static void Main(string[] args)
{
GetBinaryInput(out var UserInput);
Console.WriteLine(UserInput);
}
Using ref:
static void GetBinaryInput(ref int UserInput)
{
UserInput = int.Parse(Console.ReadLine());
}
static void Main(string[] args)
{
int UserInput = 0;
GetBinaryInput(ref UserInput);
Console.WriteLine(UserInput);
}
The first is more conventional and clean for the case in question.
Using an instance variable UserInput accessible to all methods is useless too, because this is a parameter between methods interactions, otherwise it is this one that is useless.
Also prefer TryParse to control errors, else use exception handling.
How TryParse method works?
What's the difference between the 'ref' and 'out' keywords?
When to use in vs ref vs out
Best practice: ref parameter or return value?
Which is better, return value or out parameter?
if you're returning a value, you will need the correct type of variable to return it too, e.g:
static void Main(string[] args)
{
int output = BinaryInput();
Console.WriteLine(output);
}
static int BinaryInput()
{
UserInput = int.Parse(Console.ReadLine());
return UserInput;
}
I am new to C#. I'd be thankful if any body can show me why the following error is shown for code.
"CS5001 Program does not contain a static 'Main' method suitable for an entry point"
using System;
class test
{
void Foo(int x) { Console.WriteLine(x); }
void Foo(double x) { Console.WriteLine(x); }
void Foo(int x, float y) { Console.WriteLine(x); Console.WriteLine(y);}
void Foo(float x, int y) { Console.WriteLine(x); Console.WriteLine(y); }
void Main()
{
Foo(123); // int
Foo(123.0); // double
Foo(123, 123F); // int, float
Foo(123F, 123); // float, int
}
}
This error occurs when Main method is defined with incorrect signature. This error also occurs if Main, is defined with the wrong case, such as lower-case main.
Main must be declared as static and it must return void or int, and it
must have either no parameters or else one parameter of type string[]
Define your main method like this -
static void Main()
OR like this -
static void Main(string[] args)
Have a look at this link for more information
Your fixed code should look like this:
using System;
class test
{
static void Foo(int x) { Console.WriteLine(x); }
static void Foo(double x) { Console.WriteLine(x); }
static void Foo(int x, float y) { Console.WriteLine(x); Console.WriteLine(y); }
static void Foo(float x, int y) { Console.WriteLine(x); Console.WriteLine(y); }
static void Main()
{
Foo(123); // int
Foo(123.0); // double
Foo(123, 123F); // int, float
Foo(123F, 123); // float, int
}
}
Remove <OutputType>Exe</OutputType> in project file (.csproj)
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int number1,number2;
number1 = int.Parse(Console.ReadLine());
number2 = int.Parse(Console.ReadLine());
Console.WriteLine("the sum of numbers are " +" "+ (number1 + number2));
Console.ReadKey();
DoStuff(number1,number2);
}
public int DoStuff(int num1,int num2)
{
int result = num1 + num2;
return result;
}
}
}
What am I doing wrong?
You are not allowed to call a non-static method inside a static method. If you want to invoke then you need a object reference. This is because the static methods cannot be instantiate. So the method DoStuff should be static, hence its signature may looks like this:
public static int DoStuff(int num1,int num2)
{
int result = num1 + num2;
return result;
}
I have one more suggestion for you to improve your code; it is nothing but use int.TryParse instead for simple .Parse. Which helps you to handle FormatException too. So the complete code will looks like:
class Program
{
static void Main(string[] args)
{
int number1, number2;
if (int.TryParse(Console.ReadLine(), out number1) && int.TryParse(Console.ReadLine(), out number2))
{
Console.WriteLine("the sum of numbers are :{0}", DoStuff(number1, number2));
}
else
Console.ReadKey();
}
public static int DoStuff(int num1, int num2)
{
int result = num1 + num2;
return result;
}
}
You are using DoStuff as a static method.
You should do the following:
...
Console.ReadKey();
var program = new Program();
program.DoStuff(number1, number2);
...
So create an instance of your class and call the method upon it.
If you do want to use the method in a static way, you should declare it statically:
public static int DoStuff(int num1,int num2)
{
int result = num1 + num2;
return result;
}
See the "static" keyword after "public".
From C# Specifications:
1.6.6.3 Static and instance methods
A method declared with a static modifier is a static method. A static method does not operate on a
specific instance and can only directly access static members. A
method declared without a static modifier is an instance method. An
instance method operates on a specific instance and can access both
static and instance members. The instance on which an instance method
was invoked can be explicitly accessed as this. It is an error to
refer to this in a static method.
Your Main method is static, so it can only access static members. Solution is to change:
public static int DoStuff(int num1,int num2)
From a static function you can call only static functions.
So change your DoStuff function to be static:
public static int DoStuff(int num1,int num2)
{
int result = num1 + num2;
return result;
}
For more info: Static classes
A non-static member belongs to an instance. It's meaningless without somehow resolving which instance of a class you are talking about. In a static context, you don't have an instance, that's why you can't access a non-static member without explicitly mentioning an object reference.
In fact, you can access a non-static member in a static context by specifying the object reference explicitly:
class HelloWorld {
int i;
public HelloWorld(int i) { this.i = i; }
public static void Print(HelloWorld instance) {
Console.WriteLine(instance.i);
}
}
var test = new HelloWorld(1);
var test2 = new HelloWorld(2);
HelloWorld.Print(test);
Without explicitly referring to the instance in the Print method, how would it know it should print 1 and not 2?
Either you can stuff the Method with static as show in below or
public static int DoStuff(int num1,int num2)
{
int result = num1 + num2;
return result;
}
Static methods:These are called with the type name. No instance is required—this makes them slightly faster. Static methods can be public or private.
Info:
Static methods use the static keyword, usually as the first keyword or the second keyword after public.
Warning:
A static method cannot access non-static class level members. It has no "this" pointer.
Instance:
An instance method can access those members, but must be called through an instantiated object. This adds indirection.
For Example:
class Program
{
static void MethodA()
{
Console.WriteLine("Static method");
}
void MethodB()
{
Console.WriteLine("Instance method");
}
static char MethodC()
{
Console.WriteLine("Static method");
return 'C';
}
char MethodD()
{
Console.WriteLine("Instance method");
return 'D';
}
static void Main()
{
//
// Call the two static methods on the Program type.
//
Program.MethodA();
Console.WriteLine(Program.MethodC());
//
// Create a new Program instance and call the two instance methods.
//
Program programInstance = new Program();
programInstance.MethodB();
Console.WriteLine(programInstance.MethodD());
Console.ReadLine();
}
}
I would like to call a methodA with parameters already specified from another method.
So I want to pass the method call and arguments as a parameter to MethodB and once it's done some processing, call the MethodA with arguments specified.
I know i can pass the call as a methodB as a delegate parameter and then also pass the parameters like so :
static void Main( string[] args )
{
MethodB(1, 2, Add);
Console.ReadLine();
}
public static void Add(int i, int j)
{
Console.WriteLine(i+j);
}
static public class DelegateWithDelegateParameter
{
public static void MethodB(int param1, int param2, Action<int, int> dAction)
{
dAction(param1, param2);
}
}
Wondering, if it's possible to do this with the parameters already specified rather than having to pass parameters ParamA,ParamB to MethodB from Main already specified. Was just wondering. Hope this make sense, please let me know if you want more detail.
If I'm following what you are asking, to get what you want you need to wrap your call to Add in a delegate that holds it's parameters. This is easy to do using lamda syntax:
static void Main( string[] args )
{
MethodB(() => Add(1, 2));
Console.ReadLine();
}
public static void Add(int i, int j)
{
Console.WriteLine(i+j);
}
static public class DelegateWithDelegateParameter
{
public static void MethodB(Action dAction)
{
dAction();
}
}
The statement () => Add(1,2) creates a new Action delegate that is defined to call Add() with the parametes 1,2.
I think what you want is:
static object InvokeMethod(Delegate method, params object[] args){
return method.DynamicInvoke(args);
}
static int Add(int a, int b){
return a + b;
}
static void Test(){
Console.WriteLine(InvokeMethod(new Func<int, int, int>(Add), 5, 4));
}
You can do it through Delegate. declare a delegate first and hook your method to it like
public delegate void adddelegate(int a, int b);
class Program
{
static void Main(string[] args)
{
adddelegate adddel = new adddelegate(Add);
DelegateWithDelegateParameter.MethodB(1, 2, adddel);
Console.ReadLine();
}
public static void Add(int i, int j)
{
Console.WriteLine(i + j);
}
}
static public class DelegateWithDelegateParameter
{
public static void MethodB(int param1, int param2, adddelegate dAction)
{
dAction(param1, param2);
}
}
I have a console application with a Main method and a function.
How can I make a function call from the Main method?
I know the code below won't work
static void Main(string[] args)
{
string btchid = GetCommandLine();// GetCommandline is a mthod which returns a string
}
There's also
var p = new Program();
string btchid = p.GetCommandLine();
Make the GetCommandLine static!
namespace Lab
{
public static class Program
{
static string GetCommandLine()
{
return "Hellow World!";
}
static void Main(string[] args)
{
System.Console.WriteLine(GetCommandLine());
System.Console.ReadKey();
}
}
}
You can change the function as a static and call it . Thats all.
static class Program
{
[STAThread]
static void Main()
{
string btchid = Program.GetCommandLine();
}
private static string GetCommandLine()
{
string s = "";
return s;
}
}
A linear search approach to your problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LinearSearch
{
class Program
{
static void Main(string[] args)
{
int var1 = 50;
int[] arr;
arr = new int[10]{10,20,30,40,50,60,70,80,90,100};
int retval = linearsearch(arr,var1);
if (retval >= 1)
{
Console.WriteLine(retval);
Console.Read();
}
else
{ Console.WriteLine("Not found"); Console.Read(); }
}
static int linearsearch(int[] arr, int var1)
{
int pos = 0;
int posfound = 0;
foreach (var item in arr)
{
pos = pos + 1;
if (item == var1)
{
posfound = pos;
if (posfound >= 1)
break;
}
}
return posfound;
}
}
}
GetCommandLine must be a static function
string btchid = classnamehere.GetCommandLine();
Assuming that GetCommandLine is static
Something like this:
[STAThread]
static void Main(string[] args) {
string btchid = GetCommandLine();// GetCommandline is a mthod which returns a string
}
static string GetCommandLine(){
return "Some command line";
}