CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8
  1. #1
    Join Date
    Dec 2011
    Posts
    3

    Exclamation Reference data type object

    HEY this is my first posting here,, my doubt is 2 fold :P here goes

    1.OK, i know that value data types go into stack and reference data types go into heap,, this is my understanding of this,, suppose there is an integer variable x = 30, then the stack will hold the address of the variable x which is represented in hexadecimal gibberish .. and in the case of reference type, suppose object data type refers to the variable x ,, so does that mean the heap memory will contain the memory address for the object data type that contains the memory address of variable x which holds the value 30 :P

    2.My second doubt is regarding a code snippet i have come across, It is an MCTS question btw ,,
    ok so we have a custom control called OrderForm made in ASP.Net 3.5.

    1.public delegate void CheckOrderFormEventHandler (EventArgs e);
    2.private static readonly object CheckOrderFormKey = new object();

    3.public event CheckOrderFormEventHandler CheckOrderForm
    {
    4. add { Events.AddHandler ( CheckOrderFormKey, value) ; }
    5. remove { Events.RemoveHandler ( CheckOrderFormKey, value) ; }
    }

    So here we are trying to create an event for the custom control and for that we require a delegate which is done in line 1 and the actual event is declared in step 3, some object is declared in step 2 which is readonly, my DOUBT is this,, what happens in steps 4 and 5 what is this add/remove { } construct? and can somebody explain wht is the purpose of events.addhandler/removehandler and wht is the earlier instantiated object checkorderformkey doing in the argumentslist? wht is the second argument??

    im reqd to write the eventhandler code

    this is the answer
    1.protected virtual void OnCheckOrderForm(EventArgs e)
    {
    2. CheckOrderFormEventHandler checkOrderForm= Events[CheckOrderFormKey] as CheckOrderFormEventHandler;
    4if (checkOrderForm!=null)
    5.checkOrderForm(e);
    }

    whats going on in step 2
    and step4and step 5?? im totally clueless X_X

  2. #2
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,016

    Re: Reference data type object

    It's late, so I'll let someone else answer #2.

    For #1: No, the value data will be stored directly on the stack. That is, the stack will contain 30 (not a pointer to a memory location which contains 30).

    If you give this to an object in it's constructor, the value-type will be copied into the object (stored somewhere on the heap along with the new object). If you were (using unsafe code and) had a POINTER in an object referencing the value-type on the stack, then the pointer would contain the memory address of the data on the stack.

    If I am wrong about this, will someone please correct me?

    In practicality, these details rarely come up.
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  3. #3
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Reference data type object

    Quote Originally Posted by sanjayshah_cs View Post
    1.OK, i know that value data types go into stack and reference data types go into heap,, this is my understanding of this,, suppose there is an integer variable x = 30, then the stack will hold the address of the variable x which is represented in hexadecimal gibberish .. and in the case of reference type, suppose object data type refers to the variable x ,, so does that mean the heap memory will contain the memory address for the object data type that contains the memory address of variable x which holds the value 30 :P
    Actually, that's a common misconception: value types may go on the stack, but it may end up on the heap as well, in Microsoft's implementation of the language. In some other implementation, this may or may not be the case. This is an internal implementation detail, and the C# specification nowhere states that value types should go onto the stack. The fact that it's a value type has nothing to do with where it's being stored. Hoverer, I understand that you may be expected to, at some point, provide the stack/heap answer - and for practical reasons, in such cases maybe you should... But fell free to continue with a remark that Eric Lippert, a member of the C# team, would disagree.
    The real deal about value types vs reference types is pretty much about what their names say.
    Value type instances represent values themselves (or store the values themselves), and are passed around (to methods) by value (which means that when you invoke a method and pass a parameter, the method get's its own copy of the value, and thus doesn't affect your original variable). Also, value types aren't all that much about preserving the individual identity of the instances, they are more about the values themselves - kinda more like money: you don't really care if you have this one dollar bill, or that one dollar bill, it's one dollar bill either way. Similarly, you don't really care if you have this integer with the value 5, or that integer with the value of 5... Except in some special cases.
    Reference types, on the other hand, store a reference to their object which is itself stored somewhere else where it's more appropriate, like the heap (just some kind of a number, an address of sorts, a smart pointer, no one knows the details exactly). The important thing here is that in this case, when calling methods and passing a reference type as a parameter, it is the reference that get's passed by value, but it still points to the same object. So, instances of reference types are, effectively, passed by reference. You can make some alterations in the method, and these will stick when the method returns. Reference types are defined with classes, and as a C# developer, you'll be mostly defining reference types. Here, unlike with value types, it will often be important to make a distinction between two instances, even if all their fields have the same values.

    BioPhysEngr pretty much explained how value types might end up on the heap, and you can find more detail in Eric Lippert's blog I linked to.

    Quote Originally Posted by sanjayshah_cs View Post
    2.My second doubt is regarding a code snippet i have come across, It is an MCTS question btw ,,
    ok so we have a custom control called OrderForm made in ASP.Net 3.5.

    1.public delegate void CheckOrderFormEventHandler (EventArgs e);
    2.private static readonly object CheckOrderFormKey = new object();

    3.public event CheckOrderFormEventHandler CheckOrderForm
    {
    4. add { Events.AddHandler ( CheckOrderFormKey, value) ; }
    5. remove { Events.RemoveHandler ( CheckOrderFormKey, value) ; }
    }

    So here we are trying to create an event for the custom control and for that we require a delegate which is done in line 1 and the actual event is declared in step 3, some object is declared in step 2 which is readonly, my DOUBT is this,, what happens in steps 4 and 5 what is this add/remove { } construct? and can somebody explain wht is the purpose of events.addhandler/removehandler and wht is the earlier instantiated object checkorderformkey doing in the argumentslist? wht is the second argument??
    OK. Delegates are types that can refer to a method with a given signature (in this case, to any method that returns nothing, and accepts a single parameter of type EventArgs).
    A single delegate can point to zero, one or more such methods. When the delegate is invoked (which is done the same way you would do a method call), all of the methods it refers to are invoked in some order.
    So, methods can be added and removed from a delegate - for that, we usually use the += and -= operators.
    myDelegate += SomeMethod; // adds SomeMethod
    myDelegate -= SomeMethod; // removes the same SomeMethod


    Now, events are entirely based on delegates. In some ways, an event is like a property with a delegate for a backing field. (You know what properties are?) Basically, instead of just using a delegate, we use a special keyword to declare that it's an event, and to define it's name, in order to communicate it's purpose more precisely. Usually, you would just declare an event, it's type and name, and be done with it. Like this:
    public event CheckOrderFormEventHandler CheckOrderForm;

    This is pretty much like an auto-property: behind the scenes, there's a delegate (of the CheckOrderFormEventHandler type) that actually keeps track of the subscribed methods. This is how it's usually done. But, if for some reason you don't want your method subscriptions to be stored like that, you can use the so-called event property syntax, and this is what you have in your example.
    Like the get & set blocks with regular properties, the add & remove blocks in event properties define what happens when. The add block is invoked when the += operator is encountered, and the remove block is executed when the -= operator is used.

    Now, what's going on here is something that is recommended for ASP.NET coders developing their own ASP.NET controls as an optimization (see here).
    Quote Originally Posted by MSDN
    The event implementation described above is not optimized for performance. It generates one field per delegate instance, which increases storage cost when many events are defined on a control. The base class System.Web.UI.Control provides a more efficient data structure (through its Events property) for storing and retrieving event delegates. The Events property is of type EventHandlerList, which is a data structure that is designed for efficient storage and retrieval of event delegates.
    Basically, the Control class provides some sort of a key based list or a dictionary, accessible via the Event property, that is then used as an alternative, more efficient storage for the method subscriptions. Apparently, searching for the delegate in a specialized collection, and casting it back to it's appropriate type is for some reason more performant than just having it as a field...

    In any case, the object defined in the line (2) has no other purpose whatsoever than to serve as an identification key used to store and retrieve a given event. The name has no significant role here, it's only relevant to the people using the code. It's declared static, as it needs to belong to the class itself; otherwise, a different key object would be created with each class instance, and that would prevent this whole thing to work, as it would no longer be possible to assume that the correct (or any) delegate would be obtained from the Events collection.

    Quote Originally Posted by sanjayshah_cs View Post
    im reqd to write the eventhandler code

    this is the answer
    1.protected virtual void OnCheckOrderForm(EventArgs e)
    {
    2. CheckOrderFormEventHandler checkOrderForm= Events[CheckOrderFormKey] as CheckOrderFormEventHandler;
    4if (checkOrderForm!=null)
    5.checkOrderForm(e);
    }

    whats going on in step 2
    and step4and step 5?? im totally clueless X_X
    First, in step (2), the delegate that stores the methods referenced by the event in question is retrieved from the Events collection using the key-object. In order for it to be used, it needs to be type-cast back to it's original type (since the Events property stores all kinds of delegates, they are all stored, and retrieved, via the Delegate-type, the base class for all delegates). The as keyword does the type cast. Another way to do it is to use the C-style cast.
    CheckOrderFormEventHandler checkOrderForm= (CheckOrderFormEventHandler)Events[CheckOrderFormKey];
    Line (4) checks if the delegate is not null (determines if it points to any methods at all), and then the delegate is invoked in the line (5), and e is passed as the argument. This results in all the subscribed methods being called, and in the e argument being passed to all of them.

    P.S. Please use the [code][/code] tags when posting code - preserves existing formatting, easier to read, more likely to get help.

  4. #4
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Reference data type object

    To add to Cthulhu's great post, I would like to remind those beginners out there that the stack is an implementation detail.
    If you liked my post go ahead and give me an upvote so that my epee.... ahem, reputation will grow.

    Yes; I have a blog too - http://the-angry-gorilla.com/

  5. #5
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,016

    Re: Reference data type object

    Thanks for the more accurate update, Cthulhu.
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  6. #6
    Join Date
    Dec 2011
    Posts
    3

    Talking Re: Reference data type object

    Ctulhu ill never forget u [:'(]

    that blog and and the msdn link along with your answer have answered my question completely

    *SALUTE*
    *RESPECT*

  7. #7
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Reference data type object

    Quote Originally Posted by sanjayshah_cs View Post
    Ctulhu ill never forget u [:'(]
    It's Cthulhu, dammit!
    just kidding

    Quote Originally Posted by sanjayshah_cs View Post
    im reqd to write the eventhandler code

    this is the answer
    1.protected virtual void OnCheckOrderForm(EventArgs e)
    {
    2. CheckOrderFormEventHandler checkOrderForm= Events[CheckOrderFormKey] as CheckOrderFormEventHandler;
    4if (checkOrderForm!=null)
    5.checkOrderForm(e);
    }

    whats going on in step 2
    and step4and step 5?? im totally clueless X_X
    Just to add something: if you are required to write the event handler code, that this is not it. The method above is used to raise the event, not to handle it. For example, some other method changes the state of the class, and all the interested objects should be notified about this change. To achieve this, such a method would then call the OnCheckOrderForm() method, which will in turn perform the necessary check, and raise the event. Tall subscribed handler methods will then be notified.
    A handler method is simply a method that has a signature that corresponds to that defined for the delegate type. CheckOrderFormEventHandler represents methods (or accepts methods) that return nothing (void), and take an EventArgs. It just so happens that the OnCheckOrderForm() has such a signature, but that's not required. In fact, as using the base class EventArgs usually involves no event arguments at all, but is used anyway for various reasons (say, to comply with Microsoft's event model), the parameter passed is often EventArgs.Empty. This can be done directly inside OnCheckOrderForm(), so its argument list can be empty - such a setup changes nothing.

    This would be an event handler for this event, in some other class (the name of the method has no significance):

    Code:
    // inside some class...
    // ...
    
    void OrderForm_CheckOrderForm (EventArgs e) 
    {
        //do the check, update data where appropriate...
    }
    // ...
    BTW, this is a somewhat lousy name for an event. Usually, event names suggest... well, events. A better name would be OrderFormChanged, or OrderUpdated, or DataChanged, or something like that. The name CheckOrderForm sort of tells the other class what to do. But, what if the other class doesn't want to check anything, what if it only needs to be informed that something changed, and for example, log the time somewhere?

  8. #8
    Join Date
    Mar 2012
    Location
    Nigeria
    Posts
    15

    Re: Reference data type object

    Nice post... Thanks for the tutorial.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured