What is the meaning of an object of the class inside it's class-endclass definition? - oop

What is the meaning of the following code (2nd line) in which inside class uvm_resource_pool definition, instance (object) rp is created?
class uvm_resource_pool;
static local uvm_resource_pool rp = get();
// Function: get
//
// Returns the singleton handle to the resource pool
static function uvm_resource_pool get();
if(rp == null)
rp = new();
return rp;
endfunction

This is how the singleton pattern gets coded in SystemVerilog. The singleton pattern is an OOP technique that makes sure only one instance of a class type is ever constructed. The constructor as well as the object rp are declared local. The only way to retrieve an instance of a object of the class type uvm_resource_pool is to call the static method get(), which constructs it the first time called, but then the next time it will just return rp. This is also how to solve the static class initialization order fiasco. You never reference a static variable directly, you always use a get() method that constructs it on the first reference.

Related

OOP inheritance memory initialization

When you're instantiating an object of a class that inherits from a parent class the constructor calls the superclasses constructor in most langiages I know and my question is: when the superclasse's constructor is called there will effectively be an object of that type in memory, but we're creating an object of the subclass with(in this example) additional values to add to the object so how is that accomplished in memory? Is it added to the original object? Are the contents of the original object copied into a new object with space for all the variables? Or is it something completely different?
A different question that just occured to me, are class variables, like in java, kept in the data segment of the program in memory? How are classes, not the objects, stored in memory for that matter?
Thanks.
I don't really know how engine works, but I know how to test memory usage in PHP. Both scripts
class base {
public function __construct() {
}
}
$start_memory = memory_get_usage();
$object = new base;
echo memory_get_usage() - $start_memory;
and
class base {
public function __construct() {
}
}
class derived extends base {
public function __construct() {
}
}
$start_memory = memory_get_usage();
$object = new derived;
echo memory_get_usage() - $start_memory;
return the same value. It means there'is only one instance in memory, not parent + it's child, when class is extended
phpfiddles: 1st script, 2nd script
Classed are code that define its object, so they are in Code Segment of program. And all class variables are in data segment.
And when we create an object of subclass, first its parents' object are created and it is extended for subclass members. That's why subclass object has all members of its parent class.

groovy method scope when using a method reference

I have a groovy class that looks up a method reference and then invokes it. The method being invoked is a private method. When the actual class is an instance of the child class, it throws an error that it cannot find the private method, even though it is the public method in the parent that actually calls it.
In this case, I could obviously just call pMethod2() directly and that works, but I'm trying to understand why this doesn't work as written and if there's a way to correct it so it works.
class Parent {
def pMethod1() {
def m = this.&pMethod2
m() // this call fails if the calling class is of type Child
}
private def pMethod2() {}
public static void main(String[] args) {
new Child().pMethod1();
}
}
class Child extends Parent {}
It is a bit confusing, especially if you're used to C / C++. What you get when using the ".&" operator in Groovy is not an address, but an instance of MethodClosure.
The MethodClosure object contains an owner and a delegate object, which is used when resolving the method to call. In your example, the owner and delegate object will be "this", which is an instance of Child. The method to call is simply stored as a string.
So, the assignment
m = this.&pMethod2
is just a shorthand way of writing
m = new MethodClosure(this, "pMethod2")
When you invoke the m() closure, it will try to resolve (at runtime) the method by looking for methods named "pMethod2" in the owner and the delegate objects respectively. Since the owner and delegate is an instance of Child, it will not find private methods located in Parent.
To make your example work you must make sure that the method is visible to the owner and/or delegate of the closure.
This can be done several ways, for instance by changing the access modifier of pMethod2 to protected, or by creating the closure with an instance of Parent; something like this:
m = new Parent().&pMethod2
Note that is is irrelevant that you created the MethodClosure instance in a method where pMethod2 is actually visible. It is also irrelevant that you invoke the closure in a method where it is visible. The method is not visible to the owner or delegate of the MethodClosure, which is what is being used when resolving the method.

Can a class return an object of itself

Can a class return an object of itself.
In my example I have a class called "Change" which represents a change to the system, and I am wondering if it is in anyway against design principles to return an object of type Change or an ArrayList which is populated with all the recent Change objects.
Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.
In C#, an example might be:
public class Change
{
public int ChangeID { get; set; }
private Change(int changeId)
{
ChangeID = changeId;
LoadFromDatabase();
}
private void LoadFromDatabase()
{
// TODO Perform Database load here.
}
public static Change GetChange(int changeId)
{
return new Change(changeId);
}
}
Yes it can. In fact, that's exactly what a singleton class does. The first time you call its class-level getInstance() method, it constructs an instance of itself and returns that. Then subsequent calls to getInstance() return the already-constructed instance.
Your particular case could use a similar method but you need some way of deciding the list of recent changes. As such it will need to maintain its own list of such changes. You could do this with a static array or list of the changes. Just be certain that the underlying information in the list doesn't disappear - this could happen in C++ (for example) if you maintained pointers to the objects and those objects were freed by your clients.
Less of an issue in an automatic garbage collection environment like Java since the object wouldn't disappear whilst there was still a reference to it.
However, you don't have to use this method. My preference with what you describe would be to have two clases, changelist and change. When you create an instance of the change class, pass a changelist object (null if you don't want it associated with a changelist) with the constructor and add the change to that list before returning it.
Alternatively, have a changelist method which creates a change itself and returns it, remembering the change for its own purposes.
Then you can query the changelist to get recent changes (however you define recent). That would be more flexible since it allows multiple lists.
You could even go overboard and allow a change to be associated with multiple changelists if so desired.
Another reason to return this is so that you can do function chaining:
class foo
{
private int x;
public foo()
{
this.x = 0;
}
public foo Add(int a)
{
this.x += a;
return this;
}
public foo Subtract(int a)
{
this.x -= a;
return this;
}
public int Value
{
get { return this.x; }
}
public static void Main()
{
foo f = new foo();
f.Add(10).Add(20).Subtract(1);
System.Console.WriteLine(f.Value);
}
}
$ ./foo.exe
29
There's a time and a place to do function chaining, and it's not "anytime and everywhere." But, LINQ is a good example of a place that hugely benefits from function chaining.
A class will often return an instance of itself from what is sometimes called a "factory" method. In Java or C++ (etc) this would usually be a public static method, e.g. you would call it directly on the class rather than on an instance of a class.
In your case, in Java, it might look something like this:
List<Change> changes = Change.getRecentChanges();
This assumes that the Change class itself knows how to track changes itself, rather than that job being the responsibility of some other object in the system.
A class can also return an instance of itself in the singleton pattern, where you want to ensure that only one instance of a class exists in the world:
Foo foo = Foo.getInstance();
The fluent interface methods work on the principal of returning an instance of itself, e.g.
StringBuilder sb = new StringBuilder("123");
sb.Append("456").Append("789");
You need to think about what you're trying to model. In your case, I would have a ChangeList class that contains one or more Change objects.
On the other hand, if you were modeling a hierarchical structure where a class can reference other instances of the class, then what you're doing makes sense. E.g. a tree node, which can contain other tree nodes.
Another common scenario is having the class implement a static method which returns an instance of it. That should be used when creating a new instance of the class.
I don't know of any design rule that says that's bad. So if in your model a single change can be composed of multiple changes go for it.

What is the use of making constructor private in a class?

Why should we make the constructor private in class? As we always need the constructor to be public.
Some reasons where you may need private constructor:
The constructor can only be accessed from static factory method inside the class itself. Singleton can also belong to this category.
A utility class, that only contains static methods.
By providing a private constructor you prevent class instances from being created in any place other than this very class. There are several use cases for providing such constructor.
A. Your class instances are created in a static method. The static method is then declared as public.
class MyClass()
{
private:
MyClass() { }
public:
static MyClass * CreateInstance() { return new MyClass(); }
};
B. Your class is a singleton. This means, not more than one instance of your class exists in the program.
class MyClass()
{
private:
MyClass() { }
public:
MyClass & Instance()
{
static MyClass * aGlobalInst = new MyClass();
return *aGlobalInst;
}
};
C. (Only applies to the upcoming C++0x standard) You have several constructors. Some of them are declared public, others private. For reducing code size, public constructors 'call' private constructors which in turn do all the work. Your public constructors are thus called delegating constructors:
class MyClass
{
public:
MyClass() : MyClass(2010, 1, 1) { }
private:
MyClass(int theYear, int theMonth, int theDay) { /* do real work */ }
};
D. You want to limit object copying (for example, because of using a shared resource):
class MyClass
{
SharedResource * myResource;
private:
MyClass(const MyClass & theOriginal) { }
};
E. Your class is a utility class. That means, it only contains static members. In this case, no object instance must ever be created in the program.
To leave a "back door" that allows another friend class/function to construct an object in a way forbidden to the user. An example that comes to mind would be a container constructing an iterator (C++):
Iterator Container::begin() { return Iterator(this->beginPtr_); }
// Iterator(pointer_type p) constructor is private,
// and Container is a friend of Iterator.
Everyone is stuck on the Singleton thing, wow.
Other things:
Stop people from creating your class on the stack; make private constructors and only hand back pointers via a factory method.
Preventing creating copys of the class (private copy constructor)
This can be very useful for a constructor that contains common code; private constructors can be called by other constructors, using the 'this(...);' notation. By making the common initialization code in a private (or protected) constructor, you are also making explicitly clear that it is called only during construction, which is not so if it were simply a method:
public class Point {
public Point() {
this(0,0); // call common constructor
}
private Point(int x,int y) {
m_x = x; m_y = y;
}
};
There are some instances where you might not want to use a public constructor; for example if you want a singleton class.
If you are writing an assembly used by 3rd parties there could be a number of internal classes that you only want created by your assembly and not to be instantiated by users of your assembly.
This ensures that you (the class with private constructor) control how the contructor is called.
An example : A static factory method on the class could return objects as the factory method choses to allocate them (like a singleton factory for example).
We can also have private constructor,
to enfore the object's creation by a specific class
only(For security reasons).
One way to do it is through having a friend class.
C++ example:
class ClientClass;
class SecureClass
{
private:
SecureClass(); // Constructor is private.
friend class ClientClass; // All methods in
//ClientClass have access to private
// & protected methods of SecureClass.
};
class ClientClass
{
public:
ClientClass();
SecureClass* CreateSecureClass()
{
return (new SecureClass()); // we can access
// constructor of
// SecureClass as
// ClientClass is friend
// of SecureClass.
}
};
Note: Note: Only ClientClass (since it is friend of SecureClass)
can call SecureClass's Constructor.
You shouldn't make the constructor private. Period. Make it protected, so you can extend the class if you need to.
Edit: I'm standing by that, no matter how many downvotes you throw at this.
You're cutting off the potential for future development on the code. If other users or programmers are really determined to extend the class, then they'll just change the constructor to protected in source or bytecode. You will have accomplished nothing besides to make their life a little harder. Include a warning in your constructor's comments, and leave it at that.
If it's a utility class, the simpler, more correct, and more elegant solution is to mark the whole class "static final" to prevent extension. It doesn't do any good to just mark the constructor private; a really determined user may always use reflection to obtain the constructor.
Valid uses:
One good use of a protected
constructor is to force use of static
factory methods, which allow you to
limit instantiation or pool & reuse
expensive resources (DB connections,
native resources).
Singletons (usually not good practice, but sometimes necessary)
when you do not want users to create instances of this class or create class that inherits this class, like the java.lang.math, all the function in this package is static, all the functions can be called without creating an instance of math, so the constructor is announce as static.
If it's private, then you can't call it ==> you can't instantiate the class. Useful in some cases, like a singleton.
There's a discussion and some more examples here.
I saw a question from you addressing the same issue.
Simply if you don't want to allow the others to create instances, then keep the constuctor within a limited scope. The practical application (An example) is the singleton pattern.
Constructor is private for some purpose like when you need to implement singleton or limit the number of object of a class.
For instance in singleton implementation we have to make the constructor private
#include<iostream>
using namespace std;
class singletonClass
{
static int i;
static singletonClass* instance;
public:
static singletonClass* createInstance()
{
if(i==0)
{
instance =new singletonClass;
i=1;
}
return instance;
}
void test()
{
cout<<"successfully created instance";
}
};
int singletonClass::i=0;
singletonClass* singletonClass::instance=NULL;
int main()
{
singletonClass *temp=singletonClass::createInstance();//////return instance!!!
temp->test();
}
Again if you want to limit the object creation upto 10 then use the following
#include<iostream>
using namespace std;
class singletonClass
{
static int i;
static singletonClass* instance;
public:
static singletonClass* createInstance()
{
if(i<10)
{
instance =new singletonClass;
i++;
cout<<"created";
}
return instance;
}
};
int singletonClass::i=0;
singletonClass* singletonClass::instance=NULL;
int main()
{
singletonClass *temp=singletonClass::createInstance();//return an instance
singletonClass *temp1=singletonClass::createInstance();///return another instance
}
Thanks
You can have more than one constructor. C++ provides a default constructor and a default copy constructor if you don't provide one explicitly. Suppose you have a class that can only be constructed using some parameterized constructor. Maybe it initialized variables. If a user then uses this class without that constructor, they can cause no end of problems. A good general rule: If the default implementation is not valid, make both the default and copy constructor private and don't provide an implementation:
class C
{
public:
C(int x);
private:
C();
C(const C &);
};
Use the compiler to prevent users from using the object with the default constructors that are not valid.
Quoting from Effective Java, you can have a class with private constructor to have a utility class that defines constants (as static final fields).
(EDIT: As per the comment this is something which might be applicable only with Java, I'm unaware if this construct is applicable/needed in other OO languages (say C++))
An example as below:
public class Constants {
private Contants():
public static final int ADDRESS_UNIT = 32;
...
}
EDIT_1:
Again, below explanation is applicable in Java : (and referring from the book, Effective Java)
An instantiation of utility class like the one below ,though not harmful, doesn't serve
any purpose since they are not designed to be instantiated.
For example, say there is no private Constructor for class Constants.
A code chunk like below is valid but doesn't better convey intention of
the user of Constants class
unit = (this.length)/new Constants().ADDRESS_UNIT;
in contrast with code like
unit = (this.length)/Constants.ADDRESS_UNIT;
Also I think a private constructor conveys the intention of the designer of the Constants
(say) class better.
Java provides a default parameterless public constructor if no constructor
is provided, and if your intention is to prevent instantiation then a private constructor is
needed.
One cannot mark a top level class static and even a final class can be instantiated.
Utility classes could have private constructors. Users of the classes should not be able to instantiate these classes:
public final class UtilityClass {
private UtilityClass() {}
public static utilityMethod1() {
...
}
}
You may want to prevent a class to be instantiated freely. See the singleton design pattern as an example. In order to guarantee the uniqueness, you can't let anyone create an instance of it :-)
One of the important use is in SingleTon class
class Person
{
private Person()
{
//Its private, Hense cannot be Instantiated
}
public static Person GetInstance()
{
//return new instance of Person
// In here I will be able to access private constructor
}
};
Its also suitable, If your class has only static methods. i.e nobody needs to instantiate your class
It's really one obvious reason: you want to build an object, but it's not practical to do it (in term of interface) within the constructor.
The Factory example is quite obvious, let me demonstrate the Named Constructor idiom.
Say I have a class Complex which can represent a complex number.
class Complex { public: Complex(double,double); .... };
The question is: does the constructor expects the real and imaginary parts, or does it expects the norm and angle (polar coordinates) ?
I can change the interface to make it easier:
class Complex
{
public:
static Complex Regular(double, double = 0.0f);
static Complex Polar(double, double = 0.0f);
private:
Complex(double, double);
}; // class Complex
This is called the Named Constructor idiom: the class can only be built from scratch by explicitly stating which constructor we wish to use.
It's a special case of many construction methods. The Design Patterns provide a good number of ways to build object: Builder, Factory, Abstract Factory, ... and a private constructor will ensure that the user is properly constrained.
In addition to the better-known uses…
To implement the Method Object pattern, which I’d summarize as:
“Private constructor, public static method”
“Object for implementation, function for interface”
If you want to implement a function using an object, and the object is not useful outside of doing a one-off computation (by a method call), then you have a Throwaway Object. You can encapsulate the object creation and method call in a static method, preventing this common anti-pattern:
z = new A(x,y).call();
…replacing it with a (namespaced) function call:
z = A.f(x,y);
The caller never needs to know or care that you’re using an object internally, yielding a cleaner interface, and preventing garbage from the object hanging around or incorrect use of the object.
For example, if you want to break up a computation across methods foo, bar, and zork, for example to share state without having to pass many values in and out of functions, you could implement it as follows:
class A {
public static Z f(x, y) {
A a = new A(x, y);
a.foo();
a.bar();
return a.zork();
}
private A(X x, Y y) { /* ... */ };
}
This Method Object pattern is given in Smalltalk Best Practice Patterns, Kent Beck, pages 34–37, where it is the last step of a refactoring pattern, ending:
Replace the original method with one that creates an instance of the new class, constructed with the parameters and receiver of the original method, and invokes “compute”.
This differs significantly from the other examples here: the class is instantiable (unlike a utility class), but the instances are private (unlike factory methods, including singletons etc.), and can live on the stack, since they never escape.
This pattern is very useful in bottoms-up OOP, where objects are used to simplify low-level implementation, but are not necessarily exposed externally, and contrasts with the top-down OOP that is often presented and begins with high-level interfaces.
Sometimes is useful if you want to control how and when (and how many) instances of an object are created.
Among others, used in patterns:
Singleton pattern
Builder pattern
On use of private constructors could also be to increase readability/maintainability in the face of domain-driven design.
From "Microsoft .NET - Architecing Applications for the Enterprise, 2nd Edition":
var request = new OrderRequest(1234);
Quote, "There are two problems here. First, when looking at the code, one can hardly guess what’s going
on. An instance of OrderRequest is being created, but why and using which data? What’s 1234? This
leads to the second problem: you are violating the ubiquitous language of the bounded context. The
language probably says something like this: a customer can issue an order request and is allowed to
specify a purchase ID. If that’s the case, here’s a better way to get a new OrderRequest instance:"
var request = OrderRequest.CreateForCustomer(1234);
where
private OrderRequest() { ... }
public OrderRequest CreateForCustomer (int customerId)
{
var request = new OrderRequest();
...
return request;
}
I'm not advocating this for every single class, but for the above DDD scenario I think it makes perfect sense to prevent a direct creation of a new object.
If you create a private constructor you need to create the object inside the class
enter code here#include<iostream>
//factory method
using namespace std;
class Test
{
private:
Test(){
cout<<"Object created"<<endl;
}
public:
static Test* m1(){
Test *t = new Test();
return t;
}
void m2(){
cout<<"m2-Test"<<endl;
}
};
int main(){
Test *t = Test::m1();
t->m2();
return 0;
}

What is Delegate? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am confused that what is the actual role of a delegate?
I have been asked this question many times in my interviews, but I don't think that interviewers were satisfied with my answer.
Can anyone tell me the best definition, in one sentence, with a practical example?
I like to think of a delegate as "a pointer to a function". This goes back to C days, but the idea still holds.
The idea is that you need to be able to invoke a piece of code, but that piece of code you're going to invoke isn't known until runtime. So you use a "delegate" for that purpose. Delegates come in handy for things like event handlers, and such, where you do different things based on different events, for example.
Here's a reference for C# you can look at:
In C#, for example, let's say we had a calculation we wanted to do and we wanted to use a different calculation method which we don't know until runtime. So we might have a couple calculation methods like this:
public static double CalcTotalMethod1(double amt)
{
return amt * .014;
}
public static double CalcTotalMethod2(double amt)
{
return amt * .056 + 42.43;
}
We could declare a delegate signature like this:
public delegate double calcTotalDelegate(double amt);
And then we could declare a method which takes the delegate as a parameter like this:
public static double CalcMyTotal(double amt, calcTotalDelegate calcTotal)
{
return calcTotal(amt);
}
And we could call the CalcMyTotal method passing in the delegate method we wanted to use.
double tot1 = CalcMyTotal(100.34, CalcTotalMethod1);
double tot2 = CalcMyTotal(100.34, CalcTotalMethod2);
Console.WriteLine(tot1);
Console.WriteLine(tot2);
a delegate is simply a function pointer.
simply put you assign the method you wish to run your delegate.
then later in code you can call that method via Invoke.
some code to demonstrate (wrote this from memory so syntax may be off)
delegate void delMyDelegate(object o);
private void MethodToExecute1(object o)
{
// do something with object
}
private void MethodToExecute2(object o)
{
// do something else with object
}
private void DoSomethingToList(delMyDelegate methodToRun)
{
foreach(object o in myList)
methodToRun.Invoke(o);
}
public void ApplyMethodsToList()
{
DoSomethingToList(MethodToExecute1);
DoSomethingToList(MethodToExecute2);
}
Taken from here
Q What are delegates?
A When an object receives a request, the object can either handle the request itself or pass the request on to a second object to do the work. If the object decides to pass the request on, you say that the object has forwarded responsibility for handling the request to the second object.
Or, as an easy pseudo example: something sends a request to object1. object1 then forwards the request and itself to object2 -- the delegate. object2 processes the request and does some work. (note: link above gives good examples)
Think about delegate as about a simplified implementation of Command pattern.
A delegate is an object that can refer to a method. Thus, when we create a delegate, we are creating an object that can hold a reference to a method. Furthermore, the method can be called through this reference. Thus, a delegate can invoke the method to which it refers.
The principal advantage of a delegate is that it allows us to specify a call to a method, but the method actually invoked is determined at runtime, not at compile time.
Simple Delegate
Declaration of delegate:
delegate-modifier delegate return-type delegate-name(parameters)
Implementation of delegate:
Delegate-name delegate-object=new Delegate-name(method of class)
http://knowpacific.wordpress.com/2012/01/26/delegate/
Here I am going to explain delegates, multicast delegates and their usage..
Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer. We can say a delegate is a type that defines a method signature.
When you instantiate a delegate, you can associate its instance with any method with a compatible signature. You can invoke (or call) the method through the delegate instance.
Delegates are used to pass methods as arguments to other methods.
Event handlers are nothing more than methods that are invoked through delegates.
Advantages of using delegates are,
Encapsulating the method's call from caller
Effective use of delegate improves the performance of application
Used to call a method asynchronously.
There are some properties of delegates are
Delegates are like C++ function pointers but are type safe.
Delegates allow methods to be passed as parameters.
Delegates can be used to define callback methods.
Delegates can be chained together; for example, multiple methods can be called on a single event.
Methods do not have to match the delegate signature exactly.
public delegate type_of_delegate delegate_name() // Declaration
You can use delegates without parameters or with parameter list
If you are referring to the method with some data type then the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer. Here I am giving an example with String.
The following example shows a delegate operation:
namespace MyDelegate
{
class Program
{
private delegate void Show(string s);
// Create a method for a delegate.
public static void MyDelegateMethod(string me
ssage)
{
System.Console.WriteLine(message);
}
static void Main(string[] args)
{
Show p = MyDelegateMethod;
p("My Delegate");
p.Invoke("My Delegate");
System.Console.ReadLine();
}
}
}
What is Multicast Delegate?
It is a delegate which holds the reference of more than one method. Multicast delegates must contain only methods that return void, else there is a run-time exception.
delegate void MyMulticastDelegate(int i, string s);
Class Class2
{
static void MyFirstDelegateMethod(int i, string s)
{
Console.WriteLine("My First Method");
}
static void MySecondDelegateMethod(int i, string s)
{
Console.WriteLine("My Second Method");
}
static void Main(string[] args)
{
MyMulticastDelegate Method= new MyMulticastDelegate(MyFirstDelegateMethod);
Method+= new MyMulticastDelegate (MySecondDelegateMethod);
Method(1,"Hi"); // Calling 2 Methodscalled
Method-= new MyMulticastDelegate (MyFirstDelegateMethod);
Method(2,"Hi"); //Only 2nd Method calling
}
}
Here Delegate is added using the += operator and removed using the -= operator.
Delegate types are derived from the Delegate class in the .NET Framework. Delegate types are sealed—they cannot be derived.
Because the instantiated delegate is an object, it can be passed as a parameter, or assigned to a property. This allows a method to accept a delegate as a parameter, and call the delegate at some later time. This is known as an asynchronous callback.
A great explanation and practical implementation of the Delegate pattern can be found in the Google Collections Forwarding Classes (also, the Decorator pattern).
In Event communication sender does not know which object will handle the event.
Delegate is type which hold the reference of method.
Delegate has signature and holds reference to method which matches its signature
so Delegate is like type safe function pointer.
button1.Click += new System.EventHandler(button1_Click)
System.EventHandler is declared as a delegate here
In .net Events work on the concept of Delegate (like Button Click)
Delegate is used when you do not know which code to invoke at run time
So at that time Delegate is used to handle Events
http://msdn.microsoft.com/en-us/library/ms173171(v=vs.80).aspx
A delegate object
is an object that another object consults when something happens in that object. For
instance, your repair man is your delegate if something happens to your car. you go to your repair man and ask him to fix the car for you (although some prefer to repair the car themselves, in which case, they are their own delegate for their car).
A delegate is an object that represents a pointer to a function. However, it is not an ordinary function pointer in that it:
1) Is Object Oriented
2) Is type safe, i.e. it can only point to a method and you cannot read the raw memory address it is pointing to
3) Is strongly typed. It can only point to methods that match its signatures.
4) Can point to more than one method at the same time.
Delegates is mainly used with events.
The need is:
You do not want to execute a piece of code at the time when you run the program.
After running the program you want to execute that piece of code whenever an event occurs.
Example :
Console application - code can be executed only at the time you run the program. (Written inside Main method)
Windows application (user interface programming ) - code can be executed when clicking the button after running the program.
This is what they say, you do not know which method will invoke at compiling time. you know it only at runtime that is when clicking the button.
Without delegates no user interface programming is possible. Because you are executing code whenever the user makes events that is clicking button , typing in textbox, selecting dropdownlist item and so on....
A delegate is something to which a task is being delegated. The primary purpose of delegation is to decouple code and allow for greater flexibility and reuse.
In programming, and specifically object-oriented programming, this means that when a method is called to do some work, it passes the work on to the method of another object that it has a reference to. The reference could point to whatever object we wish, as long as the object conforms to a predefined set of methods. We call it "programming to an interface" (versus programming to a concrete class implementation). An interface is basically a generic template and has no implementation; it simply means a recipe, a set of methods, preconditions and postconditions (rules).
Simple example:
SomeInterface
{
public void doSomething();
}
SomeImplementation implements SomeInterface
{
public void doSomething()
{
System.err.println("Was it good for you?");
}
}
SomeCaller
{
public void doIt(SomeInterface someInterface)
{
someInterface.doSomething();
}
}
Now you see I can use whatever implementation I want at any time without changing the code in SomeCaller because the type that doIt() is passed is not concrete but rather abstract since it's an interface. In the Java world, this is often expressed in the service paradigm where you call out to a service (an object advertising itself as a service via a specific interface) and the service then calls out to delegates to help it do its work. The service's methods are named as coarse-grained tasks (makePayment(), createNewUser(), etc.), while internally it does lots if nitty-gritty work through delegation, with the delegates' types being interfaces instead of the concrete implementations.
SomeService
{
SomeInterface someImplementation = ... // assign here
SomeOtherInterface someOtherImplementation = ... // okay, let's add a second
public void doSomeWork()
{
someImplementation.doSomething();
someOtherImplementation.doSomethingElse();
}
}
(N.B.: How an implementation gets assigned is beyond the scope of this thread. Lookup inversion of control and dependency injection.)
While not really a "function pointer", a delegate might look like this is a dynamic language like PHP:
$func = 'foo';
$func();
function foo() {
print 'foo';
}
or in JavaScript you could do something like:
var func = function(){ alert('foo!'); }
func();