What's the difference of using and not using Invoke? - c#

I'm confused with using and not using Invoke.
In the following example, I see no difference with
int answer = b(10, 10);
and
int answer = b.Invoke(10, 10);
so can anyone help me with this?
thx!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TEST
{
public delegate int BinaryOp(int x, int y);
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main innvoked on thread {0}.", Thread.CurrentThread.ManagedThreadId);
BinaryOp b = new BinaryOp(add);
//int answer = b(10, 10);
int answer = b.Invoke(10, 10);
Console.WriteLine("Doing more work in Main");
Console.WriteLine("10 + 10 is {0}", answer);
Console.Read();
}
static int add(int x, int y)
{
Console.WriteLine("add innvoked on thread {0}.", Thread.CurrentThread.ManagedThreadId);
return x + y;
}
}
}

Basically there is no difference.
Specifically since a Delegate is not really a function rather a holder to a function, that class that holds the function has to have some way to Invoke it. Hence the method Invoke. On the other hand the compiler is smart enough to automatically call Invoke when you append parenthesis to a Delegate. See https://jacksondunstan.com/articles/3283.

Related

when i create and construct 2 objects of the same type, they copy each other to the last constructed object

im a noob in c#. My problem comes when i want to create 2 objects
two_digt d1,d2;
of course i got to call for two_digt(int n) to create an object. But when i do it for d1 and d2, the last one called overwrites the first. Let me introduce to you my c# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class two_digt {
private static int dgt1, dgt2;
public two_digt(int n) {//constructor
dgt1 = n % 10;
dgt2 = (n % 100)/10;
}
public void print() {//funct to show what they've got
Console.WriteLine("dgt1:"+ dgt1 );
Console.WriteLine("dgt2:"+ dgt2 );
}
}
class Program
{
static void Main(string[] args)
{
two_digt d1 = new two_digt(Convert.ToInt32(Console.ReadLine()));
d1.print();
two_digt d2 = new two_digt(Convert.ToInt32(Console.ReadLine()));
//printing each objects
d2.print();
d1.print();
Console.ReadLine();//just to keep console from closing
}
}
}
Now i will show you the program i/o:
input:
1234
8765
//as you can suggest from my code "two_digt" will took for the
//first 2 digits of both numbers
output:
//d1.print();
dgt1:4
dgt2:3
//d2.print();
dgt1:6
dgt2:5
//d1.print();
dgt1:6
dgt2:5
//What...?
that is actually my issue and i dont understand what .net framework does with data structures, please leave an answer to this ,or, if you can, leave a pro explanation.
The problem is that dgt1, dgt2 are static. Remove the static modifier and you should get separate values.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class two_digt
{
private int dgt1, dgt2;
public two_digt(int n)
{//constructor
dgt1 = n % 10;
dgt2 = (n % 100) / 10;
}
public void print()
{//funct to show what they've got
Console.WriteLine("dgt1:" + dgt1);
Console.WriteLine("dgt2:" + dgt2);
}
}
class Program
{
static void Main(string[] args)
{
two_digt d1 = new two_digt(Convert.ToInt32(Console.ReadLine()));
d1.print();
two_digt d2 = new two_digt(Convert.ToInt32(Console.ReadLine()));
//printing each objects
d2.print();
d1.print();
Console.ReadLine();//just to keep console from closing
}
}
}

Error 1 The name 'WriteAt' does not exist in the current context

I'm trying to write a game in C# that runs on my cmd on Windows and I need to be able to write to any part of the box to do that. I found WriteAt used extensively for this purpose, however it doesn't seem to work in VS 2010. I get the error: "The name WriteAt does not exist in the current context"
I have the default:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
at the top of my code. So why can't I use WriteAt?
Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GamePCL
{
class Program
{
static void Main(string[] args)
{
Console.Clear();
for (int x = 0; x < 24; x += 2)
{
WriteAt("█", x, 0);
WriteAt("█", x, 30);
}
}
}
}
When you call a method without an object or type prefix, as in this case WriteAt() (as opposed to for example Console.WriteLine(), which is called on the Console type), the method must exist in the current context, i.e. in the current class.
You copied that code from MSDN without copying the relevant method:
protected static void WriteAt(string s, int x, int y)
{
try
{
Console.SetCursorPosition(origCol+x, origRow+y);
Console.Write(s);
}
catch (ArgumentOutOfRangeException e)
{
Console.Clear();
Console.WriteLine(e.Message);
}
}

An object reference is required for the non-static field, method, or property ConsoleApplication5.Program.myFirst(int, int)

I am new to C# and programming at whole and today I started learning C#. I have reached in the function part of my tutorial book but I fail to grasp the error in my code. I am doing exactly what's written on the book and yet this error is popping out. Google couldn't help me much as most of the Google search results had complicated solutions which went above my head. So, I would appreciate if someone takes a few minutes and point me out what I am doing wrong in my code.
The IDE is showing this error:
Error 1 An object reference is required for the non-static field,
method, or property 'ConsoleApplication5.Program.myFirst(int,
int)' C:\Users\Eion\documents\visual studio
2013\Projects\ConsoleApplication5\ConsoleApplication5\Program.cs 17 25 ConsoleApplication5
And my code is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
Console.Write("First: ");
int ab = int.Parse(Console.ReadLine());
Console.Write("Second: ");
int ba = int.Parse(Console.ReadLine());
int my1Res= myFirst(ab, ba);
Console.WriteLine("The result is " + my1Res);
}
public int myFirst(int ab, int ba)
{
int myRes = ab + ba;
return myRes;
}
}
}
You need to make myFirst method static.
public static int myFirst(int ab, int ba)
You can't call a non-static method from a static context without an instance.
See Compiler Error CS0120 for more details.

Scope Resolution Operator in c# to access global variable?

I have a Program in C++
int x=100; //Global declaration
main()
{
int x=200;
{
int y;
y=x;
cout<<"Inner Block"<<endl;
cout<<x<<endl;
cout<<y<<endl
cout<<::x<<endl;
}
cout<<"Outer Block"<<"\n";
cout<<x<<"\n";
cout<<::x;
}
Output of this program is:
Inner Block
200
200
100
Outer Block
200
100
I want to try similar thing in c# but when I type ::x,i gives me error...
Please help
What I have tried is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CAScopeResolution_Operator
{
class Program
{
static int x = 100;
static void Main(string[] args)
{
int x = 200;
{
int y;
y = x;
Console.WriteLine("Inner Block");
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(Program.x);
}
Console.WriteLine("Outer Block");
Console.WriteLine(x);
Console.WriteLine(Program.x);
Console.ReadLine();
}
}
}
I have declared static x,but I dont think this is the solution to have similar code in c#... Please help
As C# does not deal with global variables as C++ does, the :: has a different meaning. It is about namespaces here, as you can identify each member by the class it belongs to.
So if you have namespaces and/or types that share an identifier but in different namespace, you can identify them using ::-operator.
using colAlias = System.Collections;
namespace System
{
class TestClass
{
static void Main()
{
// Searching the alias:
colAlias::Hashtable test = new colAlias::Hashtable();
// Add items to the table.
test.Add("A", "1");
test.Add("B", "2");
test.Add("C", "3");
foreach (string name in test.Keys)
{
// Searching the global namespace:
global::System.Console.WriteLine(name + " " + test[name]);
}
}
}
}
generates this
A 1
B 2
C 3
See here for MSDN reference.

Trying to learn about the new async features in c#

I copied this example from here
I have seen many similar examples. Most of them say they're using the Async CTP. I'm using Visual Studio 11 on Windows 8 though so that does not apply. As shown, the error says TaskEx doesn't exist. I assume I'm missing a reference but don't know which one.
This page is http://users.zoominternet.net/~charleswatson/pic.png.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static Random rnd = new Random();
static void Main(string[] args)
{
//Do some other heavy duty background task in this thread
StartHotel();
Console.WriteLine("StartHotel called..");
Console.ReadLine();
}
static void StartHotel()
{
Console.WriteLine("Starting Hotel..");
for (int i = 0; i < 10; i++)
{
string name = "Chef" + i;
CookDish(name, "Dish" + i);
Console.WriteLine("Asked {0} to start cooking at {1}", name, DateTime.Now.ToString());
}
}
static async void CookDish(string chefName, string dish)
{
//Induce a random delay
int delay = rnd.Next(1000, 4000);
//Cook is cooking - Task
await TaskEx.Delay(delay);
//Write the result - StuffAfterAwait
Console.WriteLine("Chef {0} Finished at {1}", chefName, DateTime.Now.ToString());
}
}
}
In the CTP we were unable to add new features to the Task type so we did the pragmatic thing and just made a new TaskEx type. In the final release there will be no such type; those methods will just be on Task like you'd expect.
Replace TaskEx with Task. At the top of the .cs file, you'll need:
using System.Threading.Tasks;
Much of the sample code I've seen refers to TaskEx, and the estimable Mr. Lippert seems to be indicating that's an artifact of their development process. If you're using the Developer Preview, calls like Run, WhenAll, and Delay are already methods of the class Task rather than of TaskEx. The release tools should be the same.

Categories