My C# function will not work [duplicate] - c#

This question already has answers here:
C# error: "An object reference is required for the non-static field, method, or property"
(3 answers)
Error: "an object reference is required for the non-static field, method or property..." [duplicate]
(6 answers)
An object reference is required for the non-static field, method, or property
(3 answers)
CS0120 error under vs2010 beta 2 - object reference is required
(2 answers)
Closed 5 years ago.
I have made a function called "AddNumbers" but when I call it, I get an error that says "An object reference is needed". I have placed this function outside of the Main() entry point, but I am sure it has nothing to do with placement because I tried moving it and it would still not work.
namespace FunctionPractice
{
class Program
{
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
static void Main(string[] args)
{
Console.WriteLine("Enter 2 numbers: ");
int firstNumber = Convert.ToInt16(Console.ReadLine());
int secondNumber = Convert.ToInt16(Console.ReadLine());
int result = AddNumbers(firstNumber, secondNumber);
Console.WriteLine(result);
}
}
}

Change the method declaration to
public static int AddNumbers(int number1, int number2)
Or create an instance of Program class in main method and then access the add numbers method.
namespace FunctionPractice
{
class Program
{
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
static void Main(string[] args)
{
Console.WriteLine("Enter 2 numbers: ");
int firstNumber = Convert.ToInt16(Console.ReadLine());
int secondNumber = Convert.ToInt16(Console.ReadLine());
Program program = new Program();
int result = program.AddNumbers(firstNumber, secondNumber);
Console.WriteLine(result);
}
}
}

Si main is static, AddNumbers must be static as well.

Hey your method works fine you just need to make your "AddNumbers" method static. You can't call a non-static method from a static one. Also you may want to add a read line to the end so the program doesn't just shut off once it writes to the screen. Here would be the fixed code.
class Program
{
public static int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
static void Main(string[] args)
{
Console.WriteLine("Enter 2 numbers: ");
int firstNumber = Convert.ToInt16(Console.ReadLine());
int secondNumber = Convert.ToInt16(Console.ReadLine());
int result = AddNumbers(firstNumber, secondNumber);
Console.WriteLine(result);
Console.ReadLine();
}
}

Make your function as
public static int AddNumbers(int number1, int number2).
This is because, you are calling your function from a static function which belongs to the class itself. Your function belongs to the objects of the class. So when you call static function main(), it doesn't know of which instance's AddNumbers to call. Hence the error. Please read more about static keyword.

Related

Basic C# Program Involving functions not working

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;
}

Methods not working? [duplicate]

This question already has an answer here:
C# - Why is this variable not being changed after being put through a method [duplicate]
(1 answer)
Closed 5 years ago.
Here is the block of code that I am having a bit of trouble with:
using System;
namespace TestProgram {
class Test {
static void Main() {
int number = 10;
MultiplyByTen(number);
Console.WriteLine(number);
Console.ReadKey(true);
}
static public void MultiplyByTen(int num) {
num *= 10;
}
}
}
When I run this block of code, I got 10 as the output instead of 100. My question is: Why does this happen and how to solve it?
Thanks for the help.
The problem is that when the variable number enters into the method MultiplyByTen the value is copied and the variable you are modifying inside it's in fact the copy, so, the original was not changed.
Try this instead:
public static void MultiplyByTen(ref int num)
{
num *= 10;
}
But remember you will have to call it with the ref keyword as well.
static void Main()
{
int number = 10;
MultiplyByTen(ref number);//Notice the ref keyword here
Console.WriteLine(number);
Console.ReadKey(true);
}
I recommend you to also check this out: Passing Objects By Reference or Value in C#
You need to return the value back to the function also assign the returned value to the number.
static void Main()
{
int number = 10;
number = MultiplyByTen(number);
Console.WriteLine(number);
Console.ReadKey(true);
}
static public int MultiplyByTen(int num)
{
return num *= 10;
}
Using your implementation:
using System;
namespace TestProgram {
class Test {
static void Main() {
int number = 10;
//MultiplyByTen(number);
//Console.WriteLine(number);
Console.WriteLine(MultiplyByTen(number));
Console.ReadKey(true);
}
static public int MultiplyByTen(int num) {
return num *= 10;
}
}
}

Whats the difference between ref parameter and return value (methods)

I've been studying methods and i have stumbled across the "ref" method. However both codes seem to accomplish the same thing:
class Program
{
static void Main(string[] args)
{
int number;
number = 5;
Console.WriteLine("Before method number= {0}", number);
AddThree (ref number);
Console.WriteLine("After method number={0}", number);
Console.ReadLine();
}
private static void AddThree(ref int lol) //carbon copy....so int number= 5 here
{
lol = 3;
Console.WriteLine("inside method number={0}", lol);
}
}
}
class Program
{
static void Main(string[] args)
{
int number;
int print;
number = 5;
Console.WriteLine("Before method number= {0}", number);
print =AddThree(number);
Console.WriteLine("After method number={0}", print);
Console.ReadLine();
}
private static int AddThree(int lol) //carbon copy....so int number= 5 here
{
lol = 3;
Console.WriteLine("inside method number={0}", lol);
return lol;
}
}
}
--
Is there an advantage that ref parameter has over return value? personally i dont see a massive difference..
Is there an advantage that ref parameter has over return value? personally i don't see a massive difference.
Well typically, ref is used when there's already something else being returned - e.g. for int.TryParse (which uses out, but that's similar). C# only supports returning a single value, so if you want two outputs from a method you have options of:
out parameters
ref parameters
Returning a composite value (likely to be more common in C# 7 with ValueTuple)
But there are other differences - importantly, changes to the ref parameter are visible immediately in terms of changing the original variable. That's most simply demonstrated when you have two ref parameters aliasing the same variable:
using System;
class Test
{
static void Main()
{
int x = 0;
RefTwo(ref x, ref x);
}
static void RefTwo(ref int a, ref int b)
{
Console.WriteLine(a); // 0
b = 5;
Console.WriteLine(a); // 5!
}
}
Oh, and as a little oddity, if you want a partial method to "return" a value, you basically need a ref parameter as partial methods must be void.
I would generally avoid ref parameters unless there's a very clear benefit. They make the interaction more complicated, in my view.

An object reference is required for the non-static field, method, or property DoStuff(int, int)'

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();
}
}

Result is getting 0 when using Operator Overloading in C#

Hi I have the below program and i am new to C#,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UnaryOperatorOverLoad
{
public class UnaryOperator
{
private int Number1;
private int Number2;
private int Result;
public UnaryOperator() { }
public UnaryOperator(int number1, int number2)
{
Number1 = number1;
Number2 = number2;
}
public static UnaryOperator operator +(UnaryOperator opr)
{
UnaryOperator obj = new UnaryOperator();
obj.Result = obj.Number1 + obj.Number2;
return obj;
}
public void showdata()
{
Console.WriteLine("The Sum of Two Numbers is : " + Result);
}
}
public class Program
{
static void Main(string[] args)
{
UnaryOperator opr = new UnaryOperator(20, 30);
opr.showdata();
Console.ReadLine();
}
}
}
When i execute the code , i am getting the result is 0. I am not sure where i went wrong.Please help me to rectify the code.
Your mistakes:
You are creating new UnaryOperator obj = new UnaryOperator(); in operator overloading function. So obj.Number1 and obj.Number2 's value is 0, because you have just created obj instance.
You are never calling the + operator. Add opr = +opr; statement in to the Main method.
Change your code as:
public class UnaryOperator
{
private int Number1;
private int Number2;
private int Result;
public UnaryOperator() { }
public UnaryOperator(int number1, int number2)
{
Number1 = number1;
Number2 = number2;
}
public static UnaryOperator operator +(UnaryOperator opr)
{
opr.Result = opr.Number1 + opr.Number2; // Change this line
return opr;
}
public void showdata()
{
Console.WriteLine("The Sum of Two Numbers is : " + Result);
}
}
public class Program
{
static void Main(string[] args)
{
UnaryOperator opr = new UnaryOperator(20, 30);
opr = +opr; // Add this statement
opr.showdata();
Console.ReadLine();
}
}
This line of code
UnaryOperator opr = new UnaryOperator(20, 30);
Creates a new UnaryOPerator objcet and sets the Number1 and Number2 equal to 20 and 30 correspondingly.
Then you call opr.showdata();, which will print the value of the Result variable to the console. However, since you haven't performed any addition, the value of the variable would be the default, 0. That's the reason why you got 0.
Side note: I can't get why you are tyring to overload the addition the way you do it. It's reasonable to want to overload the addition of two custom objects, like UnaryOperator. However it's seems to me a bit strange that you are trying to overload the addition using the way you do it. Also, since the + operator has two operands, you have to define them like below (that's may not the overload you thought about, but this is the proper form in general terms):
public static UnaryOperator operator +(UnaryOperator unaryOperator1, UnaryOperator unaryOperator2)
{
return new UnaryOperator(unaryOperator1.Number1+unaryOperator2.Number1,
unaryOperator1.Number2+UnaryOperator2.Number2);
}
In order for this work, you would have to change the definition of your class to the following one:
public class UnaryOperator
{
public int Number1 { get; set; }
public int Number2 { get; set; }
public UnaryOperator(int number1, int number2)
{
Number1 = number1;
Number2 = number2;
}
public static UnaryOperator operator +(UnaryOperator unaryOperator1, UnaryOperator unaryOperator2)
{
return new UnaryOperator(unaryOperator1.Number1+unaryOperator2.Number1,
unaryOperator1.Number2+unaryOperator2.Number2);
}
public void ShowData()
{
Console.WriteLine("Number1: {0}, Number2: {1}", Number1, Number2);
}
}
The the Main method should change to the following one:
public class Program
{
static void Main(string[] args)
{
// Declare the first UnaryOperator object.
UnaryOperator opr1 = new UnaryOperator(20, 30);
// Declare the second UnaryOperator object.
UnaryOperator opr2 = new UnaryOperator(10, 40);
// Add them using the overloaded version of the + operator
UnaryOperator result = opr1+opr2;
// Show the results
result.ShowData();
Console.ReadLine();
}
}
As I stated above, this may not be exactly the version of your + operator overload, but I wrote an implementation of this overload to see it how it works. For further documentation, please look here.

Categories

Resources