ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Advanced Programming
    CSI-415
    Progress0 / 55 topics
    Topics
    1. Visual Programming Basics2. Introduction to Events3. Fundamentals of Event-Driven Programming4. Message Handling5. User Interfaces6. Graphics Device Interface7. Painting and Drawing8. Windows Management9. Input Devices10. Resources11. String and Menu Resource12. Dialogs and Windows Controls13. Common Controls14. Dynamic Link Libraries (DLLs)15. Threads and Synchronization16. Network Programming17. Building Class Libraries at the Command Line18. Class Libraries19. Using References20. Assemblies21. Private Assembly Deployment22. Shared Assembly Deployment23. Configuration Overview24. Configuration Files25. Programmatic Access to Configuration26. Using SDK Tools for Signing and Deployment27. Metadata28. Reflection29. Late Binding30. Directories and Files31. Serialization32. Attributes33. Memory Management and Garbage Collection34. Threading and Synchronization35. Asynchronous Delegates36. Application Domains37. Marshal by Value38. Marshal by Reference39. Authentication and Authorization40. Configuring Security41. Code Access Security42. Code Groups43. Evidence44. Permissions45. Role-Based Security46. Principals and Identities47. Using Data Readers48. Using Data Sets49. Interacting with XML Data50. Tracing Event Logs51. Using the Boolean Switch and Trace Switch Classes52. Print Debugging Information with the Debug Class53. Instrumenting Release Builds with the Trace Class54. Using Listeners55. Implementing Custom Listeners
    CSI-415›Marshal by Reference
    Advanced ProgrammingTopic 38 of 55

    Marshal by Reference

    8 minread
    1,368words
    Intermediatelevel

    Marshal by Reference in C#

    Marshal by Reference is a process where an object is passed between contexts (e.g., between application domains, across processes, or from managed to unmanaged code) by reference, rather than by value. This means that the object itself is not copied but a reference (or pointer) to the object is passed. This allows the receiving context to access and modify the original object, rather than working with a copy of the object’s data.

    When marshalling by reference, changes made to the object in the target context are reflected in the source context because both the source and target share the same reference to the object.

    Key Concepts

    1. Marshalling: This is the process of converting data from one format or context to another, allowing data to be transmitted between different parts of an application or system.

    2. Marshal by Reference: In this case, a reference (not a copy) to the object is passed across the context boundary. The target code can then access and modify the original object, not just a copy of it.

    3. Reference Types: Most .NET objects (instances of classes) are reference types. When you pass a reference type object by reference, both the source and destination share the same memory location for the object, and changes to the object in one context affect the object in the other.

    4. MarshalByRefObject: In .NET, objects that need to be marshaled by reference across application domains must derive from the MarshalByRefObject class. This class allows objects to be accessed remotely, across application domains, or even between processes in certain contexts (like remoting).

    1. Marshal by Reference in Application Domains

    In the context of application domains, marshalling by reference allows an object to be used across different application domains without copying the data. Instead, a reference to the object is passed, enabling both application domains to interact with the same instance.

    When an object is marshaled by reference across application domains, the CLR ensures that the object is available in both domains, but the object remains in the source domain. The target domain simply holds a reference to the original object.

    Example of Marshal by Reference with Application Domains:

    using System;
    
    public class MyClass : MarshalByRefObject
    {
        public int Value { get; set; }
    
        public MyClass(int value)
        {
            Value = value;
        }
    
        public void DisplayValue()
        {
            Console.WriteLine($"Value: {Value}");
        }
    }
    
    public class Program
    {
        public static void Main()
        {
            // Create a new application domain
            AppDomain newAppDomain = AppDomain.CreateDomain("NewAppDomain");
    
            // Create an instance of MyClass in the main AppDomain
            MyClass myObject = new MyClass(42);
    
            // Marshal by reference: pass a reference to the object to the new AppDomain
            MyClass myObjectInNewDomain = (MyClass)newAppDomain.CreateInstanceAndUnwrap(
                typeof(MyClass).Assembly.FullName, "MyClass");
    
            // Call a method from the object in the new AppDomain
            myObjectInNewDomain.DisplayValue();
    
            // Modify the original object
            myObject.Value = 100;
    
            // Display the modified value in the main AppDomain
            Console.WriteLine($"Modified Value in main AppDomain: {myObject.Value}");
    
            // Unload the application domain
            AppDomain.Unload(newAppDomain);
        }
    }
    

    In this example:

    • MyClass is derived from MarshalByRefObject to enable marshalling by reference.
    • We create an instance of MyClass in the main application domain and then pass a reference to this object to the new application domain.
    • The new application domain can access and modify the original object.
    • After modifying the Value in the main domain, the change is reflected in both domains, showing that the same reference is shared.

    2. MarshalByRefObject Class

    In .NET, to use marshal-by-reference, you must derive your class from the MarshalByRefObject class. This class enables objects to be passed by reference across different application domains, allowing remote access to the object.

    • When an object is passed by reference, no actual copy is made. Instead, a proxy object is used on the target side, which forwards method calls to the original object in the source domain.

    Here’s an example of defining a class with MarshalByRefObject:

    using System;
    
    public class MyClass : MarshalByRefObject
    {
        public int Value { get; set; }
    
        public MyClass(int value)
        {
            Value = value;
        }
    
        public void DisplayValue()
        {
            Console.WriteLine($"Value: {Value}");
        }
    }
    
    public class Program
    {
        public static void Main()
        {
            MyClass myObject = new MyClass(10);
    
            // Marshalling by reference
            MyClass refObject = myObject; // Pass the reference
    
            // Both 'myObject' and 'refObject' refer to the same object
            refObject.Value = 20;
    
            // Output will be:
            Console.WriteLine($"myObject Value: {myObject.Value}");  // Output: 20
            Console.WriteLine($"refObject Value: {refObject.Value}");  // Output: 20
        }
    }
    
    • MarshalByRefObject allows passing an object by reference, ensuring that the same object is shared between different contexts.
    • Any changes to refObject directly affect myObject because they both refer to the same memory location.

    3. Marshal by Reference in .NET Remoting

    In .NET Remoting, marshalling by reference enables the creation of remote objects that can be accessed from different application domains, machines, or processes.

    Here’s an example of using remoting with Marshal by Reference:

    Example: Creating a Remote Object

    using System;
    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
    
    public class MyClass : MarshalByRefObject
    {
        public int Value { get; set; }
    
        public MyClass(int value)
        {
            Value = value;
        }
    
        public void DisplayValue()
        {
            Console.WriteLine($"Value: {Value}");
        }
    }
    
    public class Program
    {
        public static void Main()
        {
            // Create a channel for remoting communication
            TcpChannel channel = new TcpChannel(8080);
            ChannelServices.RegisterChannel(channel, false);
    
            // Register the remote object
            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(MyClass), "MyRemoteObject", WellKnownObjectMode.SingleCall);
    
            // Wait for remote calls
            Console.WriteLine("Server is waiting for client requests...");
            Console.ReadLine();
        }
    }
    

    In this example:

    • The class MyClass derives from MarshalByRefObject, allowing it to be accessed remotely across different application domains or machines.
    • RemotingConfiguration.RegisterWellKnownServiceType makes the object available for remote calls.

    This is an example of how objects can be accessed remotely via .NET Remoting. Changes made to the remote object will be reflected across all clients accessing that object by reference.

    4. Differences Between Marshal by Value and Marshal by Reference

    Feature Marshal by Value Marshal by Reference
    Object Passing A copy of the object is passed. A reference to the original object is passed.
    Changes in Target Changes do not affect the original object. Changes are reflected in the original object.
    Memory Consumption Higher memory consumption (due to object copy). Lower memory consumption (no object copy).
    Isolation Objects in different contexts are independent. Objects are shared across contexts.
    Use Case Useful when you need to isolate data between domains. Useful when you need to share data between domains.

    5. Limitations of Marshal by Reference

    While marshalling by reference is useful in various scenarios (e.g., remote object access, cross-domain communication), there are some limitations:

    1. Dependency on Original Object: Since the target context uses a reference to the original object, any changes made to the object are reflected in the source domain. This could introduce side effects if the object is inadvertently modified.
    2. Cross-Domain Limitations: Application domains are typically designed to isolate objects. Using marshalling by reference might require additional configuration, especially in distributed scenarios (like remoting), which may be more complex than marshaling by value.
    3. Security and Trust: Objects passed by reference may introduce security issues if the target domain or context does not have appropriate access rights to the original object.

    6. Summary

    • Marshal by Reference passes a reference to the object instead of a copy. This means that both the source and target contexts share the same instance, and any changes made in one context are reflected in the other.
    • The class MarshalByRefObject is used to create objects that are marshaled by reference across application domains or processes.
    • Remoting and cross-application domain communication are common scenarios where marshalling by reference is used.
    • The main difference between Marshal by Value and Marshal by Reference is whether an object is copied (value) or referenced (reference).

    Marshalling by reference is particularly useful when you need to share state or interact with the same object across different application domains or processes, without needing to duplicate the object’s data. However, it requires careful consideration of memory management and security

    Previous topic 37
    Marshal by Value
    Next topic 39
    Authentication and Authorization

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time8 min
      Word count1,368
      Code examples0
      DifficultyIntermediate