I'm learning about delegates. This is example code (first) from a LinkedIn tutorial on C#. I am unable to identify the advantage and purpose of using the delegate. Its unclear what the reasons are we would not call the function directly. I retyped my own code (second) that appears to give a similar result.
namespace Delegates1._10._2018
{
public delegate string MyDelegate(int arg1, int arg2);
internal class Program
{
static string func1(int a, int b)
{
return (a + b).ToString();
}
static string func2(int a, int b)
{
return (a * b).ToString();
}
static void Main(string[] args)
{
MyDelegate f = func1;
Console.WriteLine("The number is: " + f(10,20));
f = func2;
Console.WriteLine("The number is: " + f(10,20));
}
}
}
internal class Program
{
public static int func1(int a, int b)
{
return (a + b);
}
public static int func2(int a, int b)
{
return (a * b);
}
static void Main(string[] args)
{
Console.WriteLine("The number is: " + func1(10, 20));
Console.WriteLine("The number is: " + func2(10, 20));
}
}
The number is: 30
The number is: 200
The delegate is just declaring the shape of a method (public delegate string MyDelegate(int arg1, int arg2);. You can change which method is called as shown in your first Main method. This is a contrived example, which doesn't have much benefit as it doesn't deal with external data or input to manipulate the behavior.
The example is bad!. Let me try to explain:
We have a Class Car, the Car does not know how to drive itself, the Person sitting in the Car, knows how to drive it. So the Car Asks to the Person (Delegate) Drive me!
public delegate int DriveMeWithSpeed(int maxForceOnPedal);
public class Car
{
DriveMeWithSpeed speedy;
public Car(DriveMeWithSpeed YourSpeed)
{
speedy = YourSpeed;
}
public void Drive()
{
if (speedy != null) speedy(100);
}
}
public class Person
{
public int IDrive(int PedalForce)
{
return 40;
}
}
public static void Main(string[] args)
{
Person Me = new Person();
Car myCar = new Car(Me.IDrive);
myCar.Drive();
}
So main concept is that the class itself does not always know the functionality of a function so it delegates this to the class who knows what to do.
Related
This is the Question I am trying to solve in C Sharp.
I am getting an error:
Error Expected ; or = (cannot specify constructor arguments in declaration)
Can anyone help me to solve this or guide me to solve this?
namespace program
{
public class Integer
{
private int intvar;
public Integer()
{
intvar = 0;
}
public Integer(int x)
{
intvar = x;
}
public void display()
{
Console.Write(intvar);
Console.Write("\n");
}
public void add(Integer x, Integer y)
{
intvar = x.intvar + y.intvar;
}
}
class Program
{
static void Main(string[] args)
{
Integer a(5),b(45);
Integer c;
c.add(a,b);
c.display();
Console.ReadLine();
}
}
}
You cannot create objects like that in C#. Im assuming you come from C++ where this syntax is possible.
In C# you have to create objects using new:
Integer foo = new Integer(45);
To create a new instance of a type, you have to invoke one of the constructors of that type using the new operator. For example:
class Program
{
static void Main(string[] args)
{
var a = new Integer(5);
var b = new Integer(45);
var c = new Integer(); //result instance
c.add(a, b);
c.display();
Console.ReadLine();
}
}
I am not able to invoke a delegate when passing an anonymous function.
Here is the code.
public class MethodCollection
{
public static void Print(Action<int, int> printNumbers)
{
}
}
public class Program
{
static void Main(string[] args)
{
MethodCollection.Print((p, q) => { p = q = 3; Console.WriteLine(p + q); });
Console.ReadLine();
}
}
The output is a blank screen.
The program does not print the expected output, i.e. 6.
Just call printNumbers.Invoke(3,3); or so in your Print method.
You should remove the p = q = 3; in your action because as Jon mentioned this will make your action ignore the numbers you pass the action.
Or it can be something like this... and I think you should see delegates basics first
helpful link to learn basics of delegates
public class MethodCollection
{
public static void Print(Action<int, int> printNumbers)
{
printNumbers.Invoke(0,0);
}
}
public class Program
{
static void Main(string[] args)
{
MethodCollection.Print((p, q) => { Console.WriteLine((p=3) + (q=3)); });
Console.ReadLine();
}
}
I have a class that parameters there can change, i'm creating a class that sorts groups of the first class, by the given parameter it needed to be sorted by.
class class1
{
private int p1;
private int p2;
//and etc depending on the need of it
}
for each parameter there is a get function.
i tried to do the following:
class class2<T>
{
private Func<T> getValue;
public class2(Func<T> getValue)
{
this.getValue = getValue;
}
public void Add(class1 cs)
{
//here is where i want to execute getValue on cs itself to compare them to one another.
}
}
I have tried doing the following in the main class:
class Program
{
static void Main(string[] args)
{
class1 c1 = new class1(1, 2);
class2<int> c2 = new class2<int>(c1.getp1)
}
}
but it only stores the the function for c1, and i cant execute it as i need it.
Is there a way to do it?
Thanks ahead for the help and sorry for the dumb explanation.
Instead of Func<T>, use Func<class1,T> (msdn docs).
class class2<T>
{
private Func<class1, T> getValue;
public class2(Func<class1, T> getValue)
{
this.getValue = getValue;
}
public void Add(class1 cs)
{
// Something like this
var val = this.getValue(class1);
// do something with val
}
}
class Program
{
static void Main(string[] args)
{
class1 c1 = new class1(1, 2);
// create the Func as a lambda and pass to the constructor.
class2<int> c2 = new class2<int>(c => c.getp1)
}
}
I haven't ran/compiled this.
Your question is a little confusing, but I think what you want is this:
class class1
{
private int _p1;
private int _p2;
//and etc depending on the need of it
public class1(int p1, int p2)
{
_p1 = p1;
_p2 = p2;
}
public int getp1()
{
return 1;
}
}
class class2<T>
{
private Func<T> getValue;
public class2(Func<T> getValue)
{
this.getValue = getValue;
}
public void Add(class1 cs)
{
//here is where i want to execute getValue on cs itself to compare them to one another.
getValue();
}
}
class Program
{
static void Main(string[] args)
{
class1 c1 = new class1(1, 2);
Func<int> getp1 = c1.getp1;
class2<int> c2 = new class2<int>(getp1);
c2.Add(c1);
}
}
Create public class in C# such that following conditions are satisfied :
The class cannot be instantiated.
A function from that class can be called by other class.
I tried this way :
public abstract class A {
public static void fun()
{
// do process.
}
}
public class B : A
{
// Now A can't be instantiated being abstract.
// And you can call its function like this :
A.fun();
}
But my answer was wrong.So, please help me out.
You can create a class like as follows to meet your goal
public class A
{
private A()
{
}
public static A GetA()
{
return new A();
}
public void Foo()
{}
}
public class B
{
public void Foo2()
{
A a = A.GetA();
a.Foo();
}
}
Making the constructor of A private would bar it from instantiating from another class. And the static method GetA will return an object of A instatiating it privately which you can use from any class.
you can use static class if you don't like allow to instantiate it use static class, The best sample for it is Math class, Also if you want to have a single instance you can use singleton.
MSDN sample:
public static class TemperatureConverter
{
public static double CelsiusToFahrenheit(string temperatureCelsius)
{
// Convert argument to double for calculations.
double celsius = System.Double.Parse(temperatureCelsius);
// Convert Celsius to Fahrenheit.
double fahrenheit = (celsius * 9 / 5) + 32;
return fahrenheit;
}
public static double FahrenheitToCelsius(string temperatureFahrenheit)
{
// Convert argument to double for calculations.
double fahrenheit = System.Double.Parse(temperatureFahrenheit);
// Convert Fahrenheit to Celsius.
double celsius = (fahrenheit - 32) * 5 / 9;
return celsius;
}
}
class TestTemperatureConverter
{
static void Main()
{
System.Console.WriteLine("Please select the convertor direction");
System.Console.WriteLine("1. From Celsius to Fahrenheit.");
System.Console.WriteLine("2. From Fahrenheit to Celsius.");
System.Console.Write(":");
string selection = System.Console.ReadLine();
double F, C = 0;
switch (selection)
{
case "1":
System.Console.Write("Please enter the Celsius temperature: ");
F = TemperatureConverter.CelsiusToFahrenheit(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
break;
case "2":
System.Console.Write("Please enter the Fahrenheit temperature: ");
C = TemperatureConverter.FahrenheitToCelsius(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Celsius: {0:F2}", C);
break;
default:
System.Console.WriteLine("Please select a convertor.");
break;
}
}
}
And for creating class singleton do this:
public sealed class MyClass
{
MyClass()
{
}
public static MyClass Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly MyClass instance = new MyClass();
}
}
I have a .Net library. say with 2 public functions. say one is Summmator which takes 2 arguments and does A+B. Another function simpleMultiplicator which takes 2 arguments: a number to multiplicate and count of times it should be multiplicated. A simpleMultiplicator function when called uses Summmator function. So it is my library. It is compiled into dll for .net4. In my programm I want to extend or modify Summator function so that when I call simpleMultiplicator it would use my modification of original Summator function. Is it possible in .net4, how to do it?
(C#, visual-C++)
It depends on how you design your classes. You state that your library exports two public functions, but they need to be defined on a class either as static or instance method, so you can make use of object-orientated principles like inheritance or polymorphism to achieve what you want.
Here is an example using inheritance:
namespace MyLibrary
{
public class MyMath
{
// Be aware of the virtual keyword which enables overriding the method
public virtual int Summmator(int a, int b)
{
return a + b;
}
public int SimpleMultiplicator(int a, int b)
{
int result = 0;
for (int i = 0; i < b; i++)
{
result = Summmator(result, a);
}
}
}
}
namespace MyProgram
{
using MyLibrary;
public class MyExtendedMath : MyMath
{
public override int Summmator(int a, int b)
{
return a + 2 * b;
}
}
public static class Program
{
public static void Main()
{
MyMath math = new MyExtendedMath();
int result = math.SimpleMultiplicator(2, 3);
Console.WriteLine(result);
}
}
}
Another way is to use polymorphism:
namespace MyLibrary
{
public interface ISummmator
{
int Summmator(int a, int b);
}
public class Summmator : ISummator
{
public int Summmator(int a, int b)
{
return a + b;
}
}
public static class MyMath
{
public static int SimpleMultiplicator(int a, int b, ISummmator summmator)
{
int result = 0;
for (int i = 0; i < b; i++)
{
result = summmator.Summmator(result, a);
}
}
}
}
namespace MyProgram
{
using MyLibrary;
public class MySummmator : ISummmator
{
public int Summmator(int a, int b)
{
return a + 2 * b;
}
}
public static class Program
{
public static void Main()
{
int result = MyMath.SimpleMultiplicator(2, 3, new MySummmator());
Console.WriteLine(result);
}
}
}
Best Regards,
Oliver Hanappi
First, I'd objectify these things. So you have a Summator which provides a sum function, and a SimpleMultiplicator which provides a multiply function. Then, you add the Summator to the SimpleMultiplicator in the default case. For example,
class SimpleMultiplicator
{
public SimpleMultiplicator()
{
this.summator = new Summator();
}
public int Mult(int a, int b)
{
// ...
this.summator.sum(something, somethingelse);
// etc
}
Then you create another constructor where you can override the default Summator:
public SimpleMultiplicator(Summator summator)
{
this.summator = summator;
}
So if you want to change the summation function, you create a new Summator-based class, override its sum() method and pass it on to the SimpleMultiplicator constructur.