C# object reference question - c#

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) { ... }

Related

Boxing process of value type fields embedded in a reference type

I am currently learning c#. Trying to clarify some questions regarding boxing.
Consider this example:
using System;
using System.IO;
using Newtonsoft.Json;
public sealed class Program
{
public int value = 0;
public static void Main()
{
var p = new Program();
var data = JsonConvert.SerializeObject(p.value);
}
}
That is the signature of theSerializeObject method:
public static string SerializeObject(object? value)
As you can see the method I use in the example requires reference to the object as a parameter, but I am passing value type instead.
I suppose that boxing must occur here. But the value field I am accessing is already allocated on a managed heap, since it is embedded field of a reference type.
The questions are:
a) Since it is obvious that local variable would get boxed in that situation (being passed as a parameter to SereializeObject()) what would happen to field access (p.value) in the example? Would the p.value be transformed into local variable and allocated on a thread stack and then get boxed?
b) What would happen if the field "value" was static? Would it get boxed?
using System;
using System.IO;
using Newtonsoft.Json;
public sealed class Program
{
public static int value = 0;
public static void Main()
{
var p = new Program();
var data = JsonConvert.SerializeObject(value);
}
}

C#: Accessing variable from another method, modifying it, returning it to the original method

Probably a very simple question, and maybe I'm not even doing it right in the first place. Done some research and having trouble understanding the second part.
Let's say I have two methods in C#, and I want to send the value of that variable to another method. This is how I've accomplished it, sending variable1s value to method 2
public void methodOne(string variable1)
{
variable1 = "testing";
myClass p = new myClass();
p.methodTwo(variable1);
}
public void methodTwo(string variable1)
{
Console.Write(variable1);
}
So this sends the information in variable1 from methodOne to methodTwo.
But what if I wanted to modify the variable in methodTwo, and then send it back to methodOne? Would I just do the same exact thing in methodTwo and utilize this again?
myClass p = new myClass();
p.methodOne(variable1);
My issue is obviously if I utilize that code, I'd get stuck in an infinite loop of going back and forth unless I added a break condition. It makes me think maybe I'm not even correctly considering how to do this, and there's an easier way I'm missing.
What you want to do is pass the variable ByRef, using the ref keyword.
using System;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Method1();
}
private static void Method1()
{
int myVar = 5;
Console.WriteLine($"myVar in Method1: {myVar}"); // 5
Method2(ref myVar);
Console.WriteLine($"myVar in Method2: {myVar}"); // 10
}
private static void Method2(ref int AnotherVar)
{
AnotherVar = 10;
}
}
}

C# Methods, returns

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.

Using delegates in C#

In C# language and .NET framework, could you help me with understanding delegates?
I was trying to check some code, and found that the results I received were unexpected for me. Here it is:
class Program
{
public static int I = 0;
static Func<string> del = new Func<string>(I.ToString);
static void Main(string[] args)
{
I = 10;
Console.WriteLine("{0}", del());
}
}
The answer was 0, but not 10. Why?
The reason is the following:
The way you declare the delegate it points directly to the ToString method of the static int instance. It is captured at the time of creation.
As flindeberg points out in the comments below, each delegate has a target and a method to be executed on the target.
In this case, the method to be executed is obviously the ToString method. The interesting part is the instance the method is executed on: It is the instance of I at the time of the creation, meaning that the delegate is not using I to get the instance to use but it stores the reference to the instance itself.
Later you change I to a different value, basically assigning it a new instance. This doesn't magically change the instance captured in your delegate, why should it?
To get the result you expect, you would need to change the delegate to this:
static Func<string> del = new Func<string>(() => I.ToString());
Like this, the delegate points to an anonymous method that executes ToString on the current I at the time of the execution of the delegate.
In this case, the method to be executed is an anonymous method created in the class in which the delegate is declared in. The instance is null as it is a static method.
Have a look at the code the compiler generates for the second version of the delegate:
private static Func<string> del = new Func<string>(UserQuery.<.cctor>b__0);
private static string cctor>b__0()
{
return UserQuery.I.ToString();
}
As you can see, it is a normal method that does something. In our case it returns the result of calling ToString on the current instance of I.
You need to pass in I to your function so that I.ToString() can be executed at the appropriate time (instead of at the time function is created).
class Program
{
public static int I = 0;
static Func<int, string> del = num => num.ToString();
static void Main(string[] args)
{
I = 10;
Console.WriteLine("{0}", del(I));
}
}
Here is how this should be done:
using System;
namespace ConsoleApplication1
{
class Program
{
public static int I = 0;
static Func<string> del = new Func<string>(() => {
return I.ToString();
});
static void Main(string[] args)
{
I = 10;
Console.WriteLine("{0}", del());
}
}
}
C# delegate enable encapsulate both an object and instance and a method. A delegate declaration defines a class that is derived from the class System.Delegate. A delegate instance encapsulates an invocations list, which is a list one or more method, each of which is referred to as callable entity.
learn more form
http://asp-net-by-parijat.blogspot.in/2015/08/what-is-delegates-in-c-how-to-declare.html
My guess is because int are passed by values not references, and for that reason when creating the delegate, it's a delegate to the method ToString of the current value of "I" (0).

c# class reference as opposed to instance reference

Can I locally reference a class in C#, instead of an instance of a class? The following code won't compile but, as an example, something like:
void someFunc()
{
var a = System.Math;
var b = a.Abs(4);
}
edit: In the real program it's not the System.Math class and I'm wanting to construct the class and return the constructed value. I didn't think originally that the context in which I wanted to use the class would be relevent, and probably it shouldn't be.
Anastasiosyal has an interesting idea with using a local Delegate to do it.
You can reference a class:
Type math = typeof(System.Math);
But you cannot call static methods on it using regular dot syntax:
// Wont compile:
math.Abs(5);
If you just want to shorten (and IMHO obfuscate) your code, you can reference classes with aliases via a using directive:
// Untested, but should work
namespace MyUnreadableCode {
using m = System.Math;
class Foo {
public static Int32 Absolut(Int32 a) {
return m.Abs(a);
}
}
}
You cannot assign a variable a value of a static class. The question is why would you want to do this, there are probably other ways that you could tackle your problem
e.g. you could use delegates to assign the operation you want to perform:
Func<int,int> operation = Math.Abs;
// then you could use it like so:
int processedValue = operation(-1);
In c# they're called Types. And you can assign them like:
Type a = typeof(SomeClass);
However, you would have to instantiate it to use it. What I believe you want is a static import like in java, but unfortunately, they do not exist in c#.
Short answer: Not like what you have above.
In C# 6.0 they introduced a static import feature, which can solve the problem.
using static System.Math;
class MyProgram
{
static void Main(string[] args)
{
var b = Abs(4); // No need to specify the name of Math class
}
}
As I understand you need to refer to the class with short name? try this (on top of the file, inside using statements section):
using m = System.Math;
later in your code:
m.Abs(...)
Makes sense?
No. It's not possible to treat a Type as a value where instance methods bind to static methods on the original type. In order to do this you would need to construct a new type which forwards it's method calls to the original type.
class MyMath {
public int Abs(int i) {
return Math.Abs(i);
}
}
var x = new MyMath();

Categories