Why to use delegates in .Net - c#

I was reading some article which was describing the use of delegates by the following example
which shows the use of multicast delegate
public delegate void ProgressReporter(int percentComplete);
class Program
{
static void Main(string[] args)
{
ProgressReporter p = WriteProgressToConsole;
p += WriteProgressToFile;
Utility.HardWork();
}
private static void WriteProgressToConsole(int percentComplete)
{
Console.WriteLine(percentComplete);
}
private static void WriteProgressToFile(int percentComplete)
{
System.IO.File.WriteAllText("progress.txt", percentComplete.ToString());
}
}
public static class Utility
{
public static void HardWork(ProgressReporter p)
{
for (int i = 0; i < 10; i++)
{
p(i);
System.Threading.Thread.Sleep(1000);
}
}
}
But from my understanding of the code I think same can be done using a class and having the same functions which define the tasks done by delegate handlers as follows
public static class ProgressReporter
{
public static void WriteProgressToConsole(int percentComplete)
{
Console.WriteLine(percentComplete);
}
public static void WriteProgressToFile(int percentComplete)
{
System.IO.File.WriteAllText("progress.txt", percentComplete.ToString());
}
}
and changing the Utility class HardWork() as follows
public static class Utility
{
public static void HardWork()
{
for (int i = 0; i < 10; i++)
{
ProgressReporter.WriteProgressToConsole(i * 10);
ProgressReporter.WriteProgressToFile(i * 10);
System.Threading.Thread.Sleep(1000);
}
}
}
So my question with respect to this code is, why do we actually need a delegate in first place?
Some of the reasons(plz correct if I am wrong) which I think we need the delegate are as follows-
If we need notification in the Program class itself, then we need delegates.
With the help of multicast delegate we can call multiple functions at the same time in place of calling them multiple times(as in my second case).

A delegate is a way to have a reference to a particular method as a variable, meaning it can change, instead of as your last example, hardcoding into the program which methods to call.
Are there way to do this without delegates? Sure, you can provide objects that override methods or use classes that implements interfaces, but delegates are cheaper in the sense that you don't need a whole type wrapped around the single method.
Examples of situations where hardcoding won't do, and interfaces/overriding methods would be more work than delegates, try looking at visual components and their events. Events in .NET use delegates. You can simply double-click on a button in the visual designer in Visual Studio and it will create the method for you and wire it up to the event by the way of a delegate. Having to create a class, or implement an interface on top of the form class would be a lot more work, and especially if you have multiple buttons that you would want to do different things, then you definitely need multiple objects implementing those interfaces.
So delegates have their place, but your examples doesn't do them justice.
Here is a LINQPad example that demonstrates that one method (DoSomething) can end up doing different things depending on the delegate provided to it:
void Main()
{
DoSomething(msg => Console.WriteLine(msg));
using (var writer = new StreamWriter(#"d:\temp\test.txt"))
{
DoSomething(msg => writer.WriteLine(msg));
}
}
public delegate void LogDelegate(string message);
public static void DoSomething(LogDelegate logger)
{
logger("Starting");
for (int index = 0; index < 10; index++)
logger("Processing element #" + index);
logger("Finishing");
}
This will first log to the console, then rerun the method and log to a file.

Use a delegate in the following circumstances
1.An eventing design pattern is used (Event handlers )
2.A class may need more than one implementation of the method
3.Thread implementation (Thread Start, sleep etc )
for more info refer
https://msdn.microsoft.com/en-us/library/ms173173.aspx:

Related

Using a Local Function over an Action as an input param

I have a method that is taking in an Action<string> (see simple example below), but in the calling method where the Action is constructed, Resharper is suggesting that a Local Function should be used.
What are the recommended practices around using Local Functions in place of Actions, does it matter, or are there gotchas to be aware of?
public void Caller()
{
string holder;
Action<string> act = s => holder = s;
void SetHolder(string s) => holder = s;
DoStuff(act);
DoStuff(SetHolder);
}
public void DoStuff(Action<string> setHolder)
{
setHolder("holders new string");
}
Taking you code and putting it through sharplab.io, we can see that the code gets lowered to:
public class Class
{
[CompilerGenerated]
private sealed class <>c__DisplayClass0_0
{
public string holder;
internal void <Caller>b__0(string s)
{
this.holder = s;
}
internal void <Caller>g__SetHolder1(string s)
{
this.holder = s;
}
}
public void Caller()
{
Class.<>c__DisplayClass0_0 #object = new Class.<>c__DisplayClass0_0();
Action<string> setHolder = new Action<string>(#object.<Caller>b__0);
this.DoStuff(setHolder);
this.DoStuff(new Action<string>(#object.<Caller>g__SetHolder1));
}
public void DoStuff(Action<string> setHolder)
{
setHolder("holders new string");
}
}
Because both act and SetHolder are closures over holder, when Caller is invoked a new closure class instance is created and new Action delegates are created for both the lambda and the local function. So the resultant code is identical for both.
Therefore, given the way you are using them here, it just comes down to readability (as many R# recommendations do). Local functions arguably have better syntax, so R# recommends you use it that way.
One of the benefits of local functions over delegates are that invoking them does not incur in a delegate instantiation and delegate invocation which is lost in your example because you are wrapping it with a delegate to pass it to DoStuff.
Have a look at the documentation to know all about local functions.

Understanding the event usage wrt delegates and registration methods

I am trying to understand the delegates and events, so far I know the concepts.
I have a question in mind and want to know if I am right.
There is a class Car. We create a public delegate (CarHandler), then we create a private member of delegate type (ListofMethods), then we create method for registering methods with this member (RegistorMethods) in this we say ListofMethods+=incoming parameter.
Then, in main program we create methods with signature same as that of the delegate(signature is return type void and parameter is string). Then, we create object of Car class. Then we register the method/methods with the delegate (method is console.writeline(incomming parameter)). Then when we invoke this class. Now, based on where in the class the ListofMethods is invoked (example:ListofMethods("Hey There");), accordingly the RegistoredMethods will fire.
So the advantage of using events instead of above example is that :
I know that we can create multiple events of the same delegate type with out creating more registration methods.
Case 1 is using only delegates and no events. And case 2 is using events. Then, In case 1, all the registered methods would get the same text as invoked by ListofHandler. To create more events (events here mean the general english meaning and not the c# events) in Case 1 we would need to create more delegate members, more methods for registering new methods with this delegate member. However, in Case of EVENTS (case 2) the different events can give their own text and the instance can then register with the event it needs and it will get it fired.
In CASE 1 we would need to create more delegate members for raising multiple events(not C# events, general English meaning), where as in case of CASE 2 (events) it is enough to create only 1 delegate member. Is that right?
Question:
Is the above para correct way to implement a CASE 3, that is like case 2, but only using delegates and not events. Please can you write a note on this in your answer
If not understood then you can ask me question. Please help me clear my doubt here.
Code for CASE 1:
public class Car
{
// 1) Define a delegate type.
public delegate void CarEngineHandler(string msgForCaller);
// 2) Define a member variable of this delegate.
//this can be public, and if public then we can avoid writing the below RegisterWithCarEngine method, but it is not safe
//because user can mess the values and call custom strings, etc
private CarEngineHandler listOfHandlers;
// 3) Add registration function for the caller.
public void RegisterWithCarEngine(CarEngineHandler methodToCall)
{
//listOfHandlers = methodToCall;
listOfHandlers += methodToCall;
}
// Internal state data.
public int CurrentSpeed { get; set; }
public int MaxSpeed { get; set; }
public string PetName { get; set; }
// Is the car alive or dead?
private bool carIsDead;
// Class constructors.
public Car()
{
MaxSpeed = 100;
}
public Car(string name, int maxSp, int currSp)
{
CurrentSpeed = currSp;
MaxSpeed = maxSp;
PetName = name;
}
// 4) Implement the Accelerate() method to invoke the delegate's
// invocation list under the correct circumstances.
public void Accelerate(int delta)
{
// If this car is "dead," send dead message.
if (carIsDead)
{
if (listOfHandlers != null)
listOfHandlers("Sorry, this car is dead...");
}
else
{
CurrentSpeed += delta;
// Is this car "almost dead"?
if (10 == (MaxSpeed - CurrentSpeed) && listOfHandlers != null)
{
listOfHandlers("Careful buddy! Gonna blow!");
}
if (CurrentSpeed >= MaxSpeed)
carIsDead = true;
else
Console.WriteLine("CurrentSpeed = {0}", CurrentSpeed);
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Delegates as event enablers *****\n");
// First, make a Car object.
Car c1 = new Car("SlugBug", 100, 10);
// Now, tell the car which method to call
// when it wants to send us messages.
c1.RegisterWithCarEngine(new Car.CarEngineHandler(OnCarEngineEvent));
// Speed up (this will trigger the events).
Console.WriteLine("***** Speeding up *****");
for (int i = 0; i < 6; i++)
c1.Accelerate(20);
Console.ReadLine();
Car c2 = new Car("SlugBug1", 100, 10);
// Speed up (this will trigger the events).
Console.WriteLine("***** Speeding up *****");
for (int i = 0; i < 6; i++)
c2.Accelerate(20);
Console.ReadLine();
}
// This is the target for incoming events.
public static void OnCarEngineEvent(string msg)
{
Console.WriteLine("\n***** Message From Car Object *****");
Console.WriteLine("=> {0}", msg);
Console.WriteLine("***********************************\n");
}
}
Code for CASE 2:
public class Car
{ // This delegate works in conjunction with the
// Car's events.
public delegate void CarEngineHandler(string msg);
// This car can send these events.
public event CarEngineHandler Exploded;
public event CarEngineHandler AboutToBlow;
...
}
public void Accelerate(int delta)
{
// If the car is dead, fire Exploded event.
if (carIsDead)
{
if (Exploded != null)
Exploded("Sorry, this car is dead...");
}
else
{ CurrentSpeed += delta;
// Almost dead?
if (10 == MaxSpeed - CurrentSpeed && AboutToBlow != null)
{
AboutToBlow("Careful buddy! Gonna blow!");
}
// Still OK!
if (CurrentSpeed >= MaxSpeed)
carIsDead = true;
else
Console.WriteLine("CurrentSpeed = {0}", CurrentSpeed);
}
}
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Events *****\n");
Car c1 = new Car("SlugBug", 100, 10);
// Register event handlers.
c1.AboutToBlow += CarIsAlmostDoomed;
c1.AboutToBlow += CarAboutToBlow;
c1.Exploded += CarExploded;
Console.WriteLine("***** Speeding up *****");
for (int i = 0; i < 6; i++)
c1.Accelerate(20);
c1.Exploded -= CarExploded;
Console.WriteLine("\n***** Speeding up *****");
for (int i = 0; i < 6; i++)
c1.Accelerate(20);
Console.ReadLine();
public static void CarAboutToBlow(string msg) { Console.WriteLine(msg); }
public static void CarIsAlmostDoomed(string msg) { Console.WriteLine("=> Critical Message from Car: {0}", msg); }
public static void CarExploded(string msg) { Console.WriteLine(msg); }
}
Your two cases are nearly identical. The only material difference is that when you use an event in your class (i.e. "case 2"), and you don't implement it explicitly, the compiler automatically generates the field that you would have had to declare in "case 1", as well as the method to allow subscription/registration.
Something that often surprises people, even occasionally those who have been using C# for some time, is a statement like mine above:
and you don't implement it explicitly
What's that statement mean? Many people don't realize that, as with a property, it is possible to either let the compiler implement the member, or to do it yourself.
In the case of the property, you implement a get and/or a set method. In the case of an event, the methods are named add and remove. And of course, if you implement it yourself, you need to also provide the backing field or other mechanism to track subscribers (just like in a property).
So, what's this all mean in your specific example? Well, to me it means that if you have event-like semantics, then you definitely should just go ahead and implement that as an actual event member. The code will all basically compile down to equivalent IL regardless of which way you do it, but using an event takes advantage of the language's high-level abstraction. This makes the code easier both to read and write, and so makes it more maintainable and less likely to contain bugs.
You can keep in mind the approach in "case 1", in case you wind up in a situation where declaring an event doesn't work (e.g. some kind of interop with a platform or API that doesn't deal with or support the .NET event paradigm). But in most situations, event is the way to go.
It seems that part of your concern is the question of the delegate members (i.e. the declared delegate types). Frankly, you have this issue regardless of which way you approach the problem. If you have a way of reusing a single delegate type for multiple event members in a class, then you can also reuse that single delegate type for the explicit field-and-registration-method approach ("case 1").
In most cases, you should not be declaring your own delegate type anyway. Just use e.g. EventHandler<T>, or one of the general purpose Action or Func types.
The difference between your two cases basically boil down to this difference:
Case 1
public class Car
{
void RegisterWithCarEngine(CarEngineHandler methodToCall);
}
Case 2
public class Car
{
event CarEngineHandler Exploded;
event CarEngineHandler AboutToBlow;
}
Case 1 is rather odd. There is nothing there to let a consumer of this class know what this method does - or when it will fire. Also, and perhaps more importantly, there is no way to detach then event handler.
Case 2 is more standard. It fits with the concept of giving a good naming convention and it is clear that these two members are events. It is therefore obvious to a consumer that they can attach and detach to these events.
You need to think about it a bit like if this where your design:
public class Car
{
void SetSpeed(string speedName, int speed);
int GetSpeed(string speedName);
}
I might then code it like this:
car.SetSpeed("Max", 50);
car.SetSpeed("Current", 10);
Console.WriteLine(car.GetSpeed("Max"));
Console.WriteLine(car.GetSpeed("Current"));
Now while this provide nominally the same functionality as your class - and same may argue that it offers even more functionality - it hides the functionality as seen by a consumer of the class.
It is far better to go with the interface provided by Case 2.
Just as a side note, you should always call your event code like this:
var x = Exploded;
if (x != null)
x("Sorry, this car is dead...");
It is possible that the delegates on Exploded can be removed between the null check and the call. The temporary assignment prevents that issue.

C# Variable Scope stopping me in my tracks

I'm fairly new to programming. The the constant issue I keep facing when I try anything for myself in C based languages is the scope.
Is there any way to use or modify a variable from within a different method or class? Is there also a way to do this without creating a new intance of a class or object? It seems to wipe the slate clean every time.
Example, I'm setting up a console text game, and I want a different background message to write to the console at certain intervals.
public static void OnTimedEvent(object scource, ElapsedEventArgs e)
{
if(Exposition.Narration == 1)
{
Console.WriteLine("The bar is hot and muggy");
}
if (Exposition.Narration == 2)
{
Console.WriteLine("You see someone stealing beer from the counter");
}
if (Exposition.Narration == 3)
{
Console.WriteLine("There is a strange smell here");
}
}
But I have no way of making different messages play. If I create the variable from within the method it will send that variable to its defult everytime it runs. If I create a new instance of an object or a class, it sends things back to the defult as well. Also, I can't modify a single class when I'm creating new instances of them all the time.
That's just one example of where its been a problem. Is there a way to have a varable with a broader scope? Or am I thinking about this the wrong way?
edit:
To put it simply can I read or change a variable from within a different method or class?
using System;
namespace Examp
{
class Program
{
public static void Main(string[] args)
{
int number = 2;
other();
}
public static void other()
{
if (Main.number == 2)
{
number = 3
}
}
}
}
While I don't think I understood completely your question, you can see here some ways to make a variable "persist" outside a method:
Static variables
Static variables are something like a global variable. You can see them through all the program if you set them as public (if you set them as internal, it's different).
A static variable can be defined as:
class MyClass
{
static int MyVariable = 4;
}
....somewhere...
void MyMethod()
{
MyClass.MyVariable = 234;
}
As you can see, you can access them anywhere.
Variables on heap
If you create an object with new operator, if you keep reference to that object, every modify you do on it, it reflects on all references to that object that you have. For example
class MyClass
{
int X;
}
static class Program
{
static void Main(string args[])
{
MyClass a = new MyClass();
a.X = 40;
Method1(a);
Method2(a);
Console.WriteLine(a.X.ToString()); // This will print 32
}
static void Method1(MyClass c)
{
c.X = 10;
}
static void Method2(MyClass c)
{
c.X = 32;
}
}
You can even use refs to edit your variables inside a method
Basically you misunderstood the concept of "scope", because you question is "which variable types exist" (global/static/local etc.). What you would like to know about scope is this: A local variable exists only within { } where it's defined.
I hope this gives you some suggestion. The answer is definitely not complete but can give you an idea.
Try to be more specific so I can change my answer.
Answer to edit 1:
No you can't change a variable in the way you want, you must add it to the class (Program in this case), try adding:
class Program
{
static int number;
....
}
Obviusly you should remove the one inside the Main method.
Also note that int can't be modified (except without a ref) inside a function if you pass them as parameters because they are copied.
The reason is quite simple: a reference to a Class instance is (at least) the same size as an int (if we are speaking about 32/64 bit systems), so it takes the same time copying it or referencing it.
You can return a value from a method after you have done your calculations if you want, like this:
int x = 3;
x = DoSomethingWithX(x);
int DoSomethingWithX(int x)
{
x += 30;
}
Class access modifiers allow you to control the members that you want the class to expose to other classes. Furthermore, static class with singleton pattern allow use to reuse the same instance across your application.
Looking at your example, it appears that you are simply trying to read the class member, hence a public property in your class should suffice. The instance of this class can be passed while initializing the class in which your OnTimedEvent method is present (this method should be changed to an instance method to access non static members of the your class).
For example,
class MyClass
{
private Exposition exposition;
// Option 1: Use parametrized constructor
// Pass the instance reference of the other class while
// constructing the object
public MyClass(Exposition exposition)
{
this.exposition = exposition;
}
// Option 2: Use an initialize method
public void Initialize(Exposition exposition)
{
this.exposition = exposition;
}
// Remove static to access instance members
public void OnTimedEvent(object scource, ElapsedEventArgs e)
{
// Better to use an enumeration/switch instead of magic constants
switch(exposition.Narration)
{
case HotAndMuggy:
Console.WriteLine("The bar is hot and muggy");;
break;
...
}
}
// Option 3: Use static properties of the Exposition class
// Note this approach should be used only if your application demands
// only one instance of the class to be created
public static void OnTimedEvent_Static(object scource, ElapsedEventArgs e)
{
// Better to use an enumeration/switch instead of magic constants
switch(Exposition.Narration)
{
case HotAndMuggy:
Console.WriteLine("The bar is hot and muggy");;
break;
...
}
}
}

Attach to Property's setter

I haven't found similiar post so I'm asking this.
Let's say I defined somewhere an application wide available static Property (I mean it's not local) and in one class I would like to know when this property is being changed. Apart from aop (transparentproxy etc.) which I think doesn't suit me well here (and I can't add that to project anyway), what are the options here?
One solution I can think of, which is probably a very nasty one, is to use some event that would be executed in the setter and just attach it in the class(es) which needs that.
Something like:
public static event EventHandler CurrentNumberChanged= delegate {};
public static int CurrentNumber
{
get
{
return currentNumber;
}
set
{
currentNumber = value;
CurrentNumberChanged(null, EventArgs.Empty);
}
}
I know it's really unsafe to use such events ( read here ). And since I would use it in asp.net makes it even more ugly. Do you have any advices ?
You could use a variation on the Observer pattern to the same effect. Not sure what your threading requirements are, and I suspect this suffers from similar dereferencing problems as How to raise custom event from a Static Class (although would have to play with the code a bit more to bottom that out):
using System;
using System.Collections.Generic;
namespace ClassLibrary1
{
public class StaticObservable
{
private static int currentNumber;
private static readonly List<IObserver> observers = new List<IObserver>();
public static int CurrentNumber
{
get{return currentNumber;}
set
{
currentNumber = value;
foreach (var observer in observers)
{
observer.NotifyChange();
}
}
}
public static void Attach(IObserver observer)
{
observers.Add(observer);
}
public static void Detach(IObserver observer)
{
observers.Remove(observer);
}
}
public interface IObserver
{
void NotifyChange();
}
public class ObserverImpl : IObserver
{
public void NotifyChange()
{
Console.Out.WriteLine("Number has changed");
}
}
public class AppWrapper
{
public static void Main (string[] args)
{
Console.ReadLine();
var observerImpl1 = new ObserverImpl();
var observerImpl2 = new ObserverImpl();
StaticObservable.Attach(observerImpl1);
StaticObservable.Attach(observerImpl2);
StaticObservable.CurrentNumber = 1;
Console.ReadLine();
}
}
}
The answer you mentioned just said that if you forget to unsubscribe some instace from a static event then this instance will live forever.
EventHandler is a bit too much I think, why not just create some boolean flag with a setter in the class that needs to receive the message, and whenever CurrentNumber's setter is triggered, call the setter of that boolean flag.
I'd like to be a little more descriptive here, but the data is not sufficient to suggest actual code.

C#: Creating an instance of an abstract class without defining new class

I know it can be done in Java, as I have used this technique quite extensively in the past. An example in Java would be shown below. (Additional question. What is this technique called? It's hard to find an example of this without a name.)
public abstract class Example {
public abstract void doStuff();
}
public class StartHere{
public static void main(string[] args){
Example x = new Example(){
public void doStuff(){
System.out.println("Did stuff");
}
};
x.doStuff();
}
}
Now, my main question would be, can this also be done in C#, and if so, how?
The Java technique is called "Anonymous inner class", and there is no equivalent in C#.
With lamba expressions and class initializers you can get the same behaviour with a bit of effort.
public class Example {
public Action DoStuff;
public Action<int> DoStuffWithParameter;
public Func<int> DoStuffWithReturnValue;
}
class Program {
static void Main(string[] args) {
var x = new Example() {
DoStuff = () => {
Console.WriteLine("Did Stuff");
},
DoStuffWithParameter = (p) => {
Console.WriteLine("Did Stuff with parameter " + p);
},
DoStuffWithReturnValue = () => { return 99; }
};
x.DoStuff();
x.DoStuffWithParameter(10);
int value = x.DoStuffWithReturnValue();
Console.WriteLine("Return value " + value);
Console.ReadLine();
}
}
One problem with this solution that I just realized is that if you were to create fields in the Example class, the lambda expressions would not be able to access those fields.
However, there is no reason that you could not pass the instance of Example to the lambda expressions which would give them access to any public state that example might hold. AFAIK that would be functionally equivalent to the Java Anonymous Inner Class.
P.S. If you are going to vote an answer down, do us all a favour and add a comment as to why you disagree :-)
Typically, problems that are solved with anonymous inner classes in Java are solved in a much cleaner fashion using delegates in .Net. Your example is a little too simplistic to determine your intent. If your intent by using the abstract class is to pass around a "behavior" think about just using an Action delegate instead.
public class StartHere{
public static void main(string[] args){
Action doStuff = () => Console.WriteLine("Did stuff");
executeSomething(doStuff);
}
public static void executeSomething(Action action)
{
action();
}
}
That can't be done in C#; you need to declare a new class type. The closest you can get in C# is probably a named nested class:
public class StartHere{
private class Foo : Example {
public override void doStuff()
{
Console.WriteLine("did stuff");
}
}
public static void Main(string[] args){
Example x = new Foo();
x.doStuff();
}
}
This is not supported in C#, and if it were up to me it shouldn't be so either.
The proliferation of inner classes in java is mainly due to the lack of delegates or lambdas, which C# has. So while this type of functionality currently is "your only hope" in java, you can usually use other mechanisms in C# to achieve the same ends. Java feels like playing the piano with one hand in this regard.
(Admittedly a lot of us have gotten quite good at this one-handed playing; and now it seems like we have to wait at least until java 8 for closures...)
Since your class represents only an action, you can use a delegate in your case, there is an existing delegate :
public delegate void Action();
This is the exact equivalent of your class.
And the déclaration of your anonymous class is even cleaner :
Action action = () => Console.WriteLine("Hello world");
action(); // invoke
you can even use closure :
public void Hello(string name)
{
Action action = () => Console.WriteLine("Hello " + name);
action(); // will call the above lambda !
}
While all good answers, most of the work arounds suggested rely on C# 3.0
So, for the sake of completeness, I'll add another solution that uses neither lambdas nor Func type (Granted that, as Matt Olenik mentioned in the comments, one could generalize the below delegates to work the same way.). For those, like me who may still be working with C# 2.0. Maybe not the best solution, but it works.
public class Example
{
public delegate void DoStuffDelecate();
public DoStuffDelecate DoStuff;
public delegate void DoStuffWithDelecate(int n);
public DoStuffWithDelecate DoStuffWithParameter;
public delegate int DoStuffWithReturnDelecate();
public DoStuffWithReturnDelecate DoStuffWithReturnValue;
}
class Program
{
static int MethodWithReturnValue()
{
return 99;
}
static void MethodForDelecate()
{
Console.WriteLine("Did Stuff");
}
static void MethodForDelecate(int n)
{
Console.WriteLine("Did Stuff with parameter " + n);
}
static void Main(string[] args)
{
var x = new Example();
x.DoStuff = MethodForDelecate;
x.DoStuffWithParameter = MethodForDelecate;
x.DoStuffWithReturnValue = MethodWithReturnValue;
x.DoStuff();
x.DoStuffWithParameter(10);
int value = x.DoStuffWithReturnValue();
Console.WriteLine("Return value " + value);
Console.ReadLine();
}
}
You are able to accomplish this with Mocking in .NET. However there is no in-language support for this feature, I think it will be available in C# 4.0. There are a number of libraries out there for Mocking, including:
Moq
RhinoMock
In short no, you have to define it as separate sub class. I think this feature is coming C# 4.0 though?
Edit: No it's not coming C# 4.0 I made that up.

Categories

Resources