This code has been taken from another website :
using System;
using System.Threading.Tasks;
public class Program {
private static Int32 Sum(Int32 n)
{
Int32 sum = 0;
for (; n > 0; n--)
checked { sum += n; }
return sum;
}
public static void Main() {
Task<int32> t = new Task<int32>(n => Sum((Int32)n), 1000);
t.Start();
t.Wait();
// Get the result (the Result property internally calls Wait)
Console.WriteLine("The sum is: " + t.Result); // An Int32 value
}
}
I don't understand the purpose of using the private static method and not any other normal public method.
Thanks
The method is static because it's used from a static context, so it can't be non-static.
The method is probably private because there's no reason to make it public.
This is because you have Main method is static and you can not call non-static method from static method without make object of that class as non-static methods are called with object.
If make the Sum method non-static you will have to call it on object of Program class
private Int32 Sum(Int32 n)
{
//your code
}
Calling will be changed as
Task<Int32> t = new Task<Int32>(n => new Program().Sum((Int32)n), 1000);
Related
I want to count the number of instance and I want to call The set accessor or Modifiers of property in c3 at the time of object creation can I?
call set at object
class a {
private static int x;
public static int X {
get {
return x;
}
set { //Call This area while oblect Creation }
}
}
class Program {
static void Main(string[] args) {
a o = new a();
a ob = new a();
Console.WriteLine("Count is: " + a.X);
}
}
To my mind, the only reasonably approach here is:
class a {
private static int x;
public static int X { get { return x; } }
public a()
{
Interlocked.Increment(ref x);
}
...
}
Now yes, the question title says "not using constructor", but: if you want to count how many instances of a type have been created - the appropriate place to put that code is in the constructor.
The Interlocked.Increment(ref x); could be replaced with x++; if you don't care about the answer being right when using multiple threads.
You could also satisfy the "not using constructor" by using a factory method:
private a() {}
public static a Create()
{
Interlocked.Increment(ref x);
return new a();
}
but if you do that, the new a() in the Main() method no longer works, and needs to be changed to a.Create().
If you don't want to use a constructor to increment your x variable you can call a static method which increments the value of x and creates a new instance of your a class:
static void Main(string[] args)
{
a o = a.incrementX();
a ob = a.incrementX();
Console.WriteLine("Count is: " + a.X);
}
The static method incrementX is defined in your class:
class a
{
private static int x;
public static int X
{
get { return x; }
set { x = value;}
}
public static a incrementX()
{
X++;
return new a();
}
}
use this:
class a
{
private static int x;
public static int X
{
get { return x; }
set { //Call This area while oblect Creation }
}
}
class Program
{
static void Main(string[] args)
{
a o = new a();
a.X += 1;
Console.WriteLine("Count is: " + a.X);
}
}
You access static field without initializing the object and so you set it's value.
Please help me with this. Let's say I have this code here...
void IScanSuccessCallback.barcodeDetected(MWResult result)
{
if (result != null)
{
try
{
var scan = Element as BarcodeScannerModal;
if (scan == null)
return;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
}
...and I want that value of MWResult result be passed to this one...
[System.Runtime.InteropServices.ComVisible(true)]
public delegate void EventScanHandler(MWResult result);
I'm really having trouble with this one.
How a basic delegate void is used. A delegate void is a method on where an object or a void is referenced. Its almost like a place holder if you have two of the same function and you need to switch the function, not so much the numbers (swith the + in 5+5 into a *, like 5*5, the example below shows how to do this. It doesent also have to be an int as a return! You can also swith it out for a void in order to do functions). In your case you want to scan the bar-code then check if it is null so I'm confused on why you would want to use a delegate void.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
//delegates are mostly defined outside of the class
public delegate int addn(int num1, int num2);
//the main class
class Program
{
//delegate functions
public static int add1(int num1, int num2)
{
return num1 + num2;
}
public static int add2(int num1, int num2)
{
return num1 * num2;
}
//entry
public static void Main()
{
//here we can reference delegates as a class. its
//called addf in this case.
//first we init add1
addn addf = new addn(add1);
Console.WriteLine(addf(5, 5));
//then we innit add2. note we dont add /*addn*/ in the beginning because
//its already defined
addf = new addn(add2);
Console.WriteLine(addf(5, 5));
//loop
while (true) ;
}
}
}
Unless you are using different versions of IScanSuccessCallback.barcodeDetected I would just call it directly, store the value in a class, then use [System.Runtime.InteropServices.ComVisible(true)]
public delegate void EventScanHandler(Class name result);
A delegate is a type that represents references to methods.
ScanSuccessCallbackImpl t = new ScanSuccessCallbackImpl();
EventScanHandler method = t.barcodeDetected;
method(new MWResult());
Does this answers your question?
Code:
using System.IO;
using System;
using System.Reflection;
using System.Collections.Generic;
class AnyClass
{
delegate void Del(string str);
static void Main()
{
List<Del> listDel = new List<Del>();
listDel.Add(delegate(string str) { });
Console.WriteLine( listDel[0].Method.ToString() );
listDel.Add(delegate(string str) { });
Console.WriteLine( listDel[1].Method.ToString() );
for (int i = 0; i < 2; i++)
{
listDel.Add(delegate(string str) { });
}
Console.WriteLine( listDel[2].Method.ToString() );
Console.WriteLine( listDel[3].Method.ToString() );
}
}
Output:
Void m__0(System.String)
Void m__1(System.String)
Void m__2(System.String)
Void m__2(System.String)
Why do the delegates instantiated in the loop "point" to the same method (m__2) whereas the ones instantiated outside the loop point to two different methods (m__0 and m__1)?
Is there any way how to instantiate delegates that point to different/unique methods inside a loop?
Example of usage: I need to have delegates as keys in a dictionary, so they need to be unique. Instantiation inside a loop is necessary to provide enough of flexibility.
Why do the delegates instantiated in the loop "point" to the same
method (m__2) whereas the ones instantiated outside the loop point to
two different methods (m__0 and m__1)?
Because behind the scenes the compiler is caching the delegate creation. When you create the first two delegates, the compiler doesn't have knowledge that they are the same, so he creates two different cached delegates and two named methods. Inside your for loop, the compiler is optimizing by only instantiating the delegate once. He can be certain that it's the same delegate each time, instantiate it once, then cache it.
When you de-compile your code, it actually looks like this:
private delegate void Del(string str);
[CompilerGenerated]
private static Launcher.Del CS$<>9__CachedAnonymousMethodDelegate3;
[CompilerGenerated]
private static Launcher.Del CS$<>9__CachedAnonymousMethodDelegate4;
[CompilerGenerated]
private static Launcher.Del CS$<>9__CachedAnonymousMethodDelegate5;
private static void Main()
{
List<Launcher.Del> listDel = new List<Launcher.Del>();
List<Launcher.Del> arg_24_0 = listDel;
if (Launcher.CS$<>9__CachedAnonymousMethodDelegate3 == null)
{
Launcher.CS$<>9__CachedAnonymousMethodDelegate3 =
new Launcher.Del(Launcher.<Main>b__0);
}
arg_24_0.Add(Launcher.CS$<>9__CachedAnonymousMethodDelegate3);
Console.WriteLine(listDel[0].Method.ToString());
List<Launcher.Del> arg_5D_0 = listDel;
if (Launcher.CS$<>9__CachedAnonymousMethodDelegate4 == null)
{
Launcher.CS$<>9__CachedAnonymousMethodDelegate4 =
new Launcher.Del(Launcher.<Main>b__1);
}
arg_5D_0.Add(Launcher.CS$<>9__CachedAnonymousMethodDelegate4);
Console.WriteLine(listDel[1].Method.ToString());
for (int i = 0; i < 2; i++)
{
List<Launcher.Del> arg_9A_0 = listDel;
if (Launcher.CS$<>9__CachedAnonymousMethodDelegate5 == null)
{
Launcher.CS$<>9__CachedAnonymousMethodDelegate5 =
new Launcher.Del(Launcher.<Main>b__2);
}
arg_9A_0.Add(Launcher.CS$<>9__CachedAnonymousMethodDelegate5);
Console.WriteLine(listDel[2 + i].Method.ToString());
}
}
[CompilerGenerated]
private static void <Main>b__0(string str)
{
}
[CompilerGenerated]
private static void <Main>b__1(string str)
{
}
[CompilerGenerated]
private static void <Main>b__2(string str)
{
}
I would definitely not rely on a delegate being a proper key for a Dictionary.
Is there any way how to instantiate delegates that point to
different/unique methods inside a loop?
You can force the delegate to be a "fresh instance" only by explicitly creating a new Del instance yourself and passing a new named method each time. There are other more "fishy" ways of doing so, but I wouldn't recommend taking those paths just to get a new delegate.
Is there any way how to instantiate delegates that point to different/unique methods inside a loop?
You can't make each loop iteration create a different method because methods are hard-coded into the assembly. Their number is fixed while the loop could be unbounded.
You can make each syntactic appearance of a lambda have a different method by using some kind of hack:
Action<int> x = i => {
if (Environment.CurrentManagedThreadId < 0 /*always false*/)
Console.WriteLine(i + uniqueIntegerHere);
};
This forces each method body to be unique and the compiler cannot ever optimize this away. You can of course pull the body into a helper method.
If you want unique delegates per loop iteration you either need to create methods at runtime or keep a set of statically compiled methods:
void F1() { }
void F2() { }
void F3() { }
...
T4 templates come to mind.
Yet another way similar to the one proposed by #usr. You can force compiler to create a new instance of delegate object using reflection method Delegate.CreateDelegate(type, this, methodInfo). The trick goes at the point where this parameter is always a new object thus forcing myMethod being called on it and thus each delegate actually represents a different context for compiler.
This requires the method for delegation to be inside a separate class, which you can instantiate. I am not sure this requirement fits you actual task. Perhaps you will be inspired for another solution based on this one...
using System.IO;
using System;
using System.Reflection;
using System.Collections.Generic;
class AnyClass
{
delegate void Del(string str);
private static Dictionary<Del, string> dict = new Dictionary<Del, string>();
static void Main()
{
List<Del> listDel = new List<Del>();
int count = 10;
for (int i = 0; i < count; i++)
{
listDel.Add(factory());
dict.Add(listDel[i ], "Delegate " + (i));
}
for (int i = 0; i < count; i++)
{
Console.WriteLine(listDel[i].Method.ToString());
listDel[i].Invoke((i).ToString());
}
Console.ReadLine();
}
public class DelegateEncapsulator
{
private int _number;
public DelegateEncapsulator(int number)
{
_number = number;
}
public void myMethod(string str) {
Console.WriteLine("Delegate " + _number + " " + str);
}
}
private static int delegateCounter = 100;
private static Del factory()
{
var obj = new DelegateEncapsulator(delegateCounter++);
var ret = (Del)Delegate.CreateDelegate(typeof(Del), obj,
typeof(DelegateEncapsulator).GetMethod("myMethod"));
return ret;
}
}
This code adds all delegates into a dictionary. You can play with number elements to be added.
Hope this helps
public class A
{
void methodA(int a){}
void methodA(ref int a){}
}
static void Main()
{
int a=1;
new classA().methodA(a);
}
In Main class, which method is called? Are methods in class A are overloaded? can overriding is possible on the bases of value or reference parameters? Please help out to make me clear.
After fixing your code:
public class ClassA
{
public void methodA(int a)
{
Console.WriteLine("Without ref");
}
public void methodA(ref int a)
{
Console.WriteLine("With ref");
}
}
class Program
{
static void Main(string[] args)
{
int i = 1;
var a = new ClassA();
a.methodA(i);
a.methodA(ref i);
Console.ReadKey(true);
}
}
You'll see that the first call will print 'Without ref' and the second 'With ref'. You could've done this yourself.
The manual says it's perfectly possible:
However, overloading can be done when one method has a ref or out parameter and the other has a value parameter, as shown in the following example.
class RefOverloadExample
{
public void SampleMethod(int i) { }
public void SampleMethod(ref int i) { }
}
new A().methodA(a);
will call the non-ref version.
new A().methodA(ref a);
will call the ref version.
In C#, you have to explicitly say if you're passing by reference.
Following calls are different
int a = 5;
methodA(a);
methodA(ref a );
ref keyword MSDN
overloading can be done when one method has a ref or out parameter and
the other has a value parameter, as shown in the following example
In your case it will call methodA(int a){} not the one with ref.
Your class should be:
public class A
{
public void methodA(int a)
{
}
public void methodA(ref int a)
{
}
}
If you want to call the overloaded method with ref keyword you need to specify ref in your method call. Like:
int a = 1;
A classAObj = new A();
classAObj.methodA(ref a);
The above code will resolved to the overloaded methodA(ref a)
public class A
{
void methodA(int a){}
void methodA(ref int a){}
}
static void Main()
{
int a=1;
new classA().methodA(a);
new classA().methodA(ref a)//You can add this to see the difference
}
Both are different from each other...
new classA().methodA(a);
new classA().methodA(ref a)
I am trying to convert Ruby's time to C#, but I am stuck now.
Here's my try:
public static class Extensions
{
public static void Times(this Int32 times, WhatGoesHere?)
{
for (int i = 0; i < times; i++)
???
}
}
I am new to C#, and maybe this one should be easy, and I know I want to use Extensionmethods. But since functions are not 'first class ' in C#, I am stuck for now.
So, what parametertype should I use for of WhatGoesHere?
You can use the Action type:
public static class Extensions
{
public static void Times(this Int32 times, Action<Int32> action)
{
for (int i = 0; i < times; i++)
action(i);
}
}
class Program
{
delegate void Del();
static void Main(string[] args)
{
5.Times(Console.WriteLine);
// or
5.Times(i => Console.WriteLine(i));
}
}
Also have a look here to learn about delegates.