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›Late Binding
    Advanced ProgrammingTopic 29 of 55

    Late Binding

    6 minread
    999words
    Intermediatelevel

    Late Binding in C#

    Late binding in C# refers to the process of resolving method calls, property accesses, or object type references at runtime, rather than at compile time (which is known as early binding). Late binding allows for more flexibility in the code because it can work with objects and methods that are determined dynamically during the execution of the program, making it useful in scenarios like working with COM objects, reflection, or interacting with types that are unknown at compile time.

    Key Concepts of Late Binding

    1. Runtime Resolution: Late binding occurs when the exact method or property to be invoked is not determined until the program is actually running.

    2. Dynamic Types: In C#, the dynamic keyword enables late binding, allowing you to work with objects whose type is not known at compile time.

    3. Reflection: Reflection in C# provides a way to inspect and interact with assemblies, types, and members (methods, properties, fields) at runtime. This is a form of late binding because it allows invoking members dynamically based on their names or types at runtime.

    Early Binding vs. Late Binding

    • Early Binding:

      • The compiler knows the type of the object and its members (methods, properties) at compile time.
      • Errors related to types or methods are detected at compile time.
      • Example: A direct method call on an object.
      var person = new Person();
      person.PrintName(); // Early binding
      
    • Late Binding:

      • The type of the object or the method to be called is not known until runtime.
      • Errors are detected at runtime, which can potentially result in runtime exceptions if a method or property doesn't exist.
      • Example: Using the dynamic keyword or reflection to call methods or access properties.
      dynamic person = new Person();
      person.PrintName(); // Late binding
      

    Late Binding with dynamic

    In C#, the dynamic keyword is used to enable late binding. When you declare an object as dynamic, the type is resolved at runtime, and the compiler doesn't check for method existence or type correctness at compile time. This allows you to invoke methods, properties, or access fields dynamically.

    Example of Late Binding Using dynamic

    using System;
    
    public class Person
    {
        public string Name { get; set; }
    
        public void PrintName()
        {
            Console.WriteLine("Name: " + Name);
        }
    }
    
    public class Program
    {
        public static void Main()
        {
            dynamic person = new Person();
            person.Name = "John Doe";  // Setting property dynamically
            person.PrintName();        // Calling method dynamically
    
            // Using late binding to access methods or properties
            dynamic unknown = "Hello, dynamic world!";
            Console.WriteLine(unknown.ToUpper());  // Calls ToUpper method dynamically
        }
    }
    

    Key Points:

    • The person variable is declared as dynamic, so its type is determined at runtime.
    • The PrintName method is called dynamically, meaning the compiler does not verify that the method exists at compile time.
    • If PrintName does not exist on the Person object, it will throw a runtime error.

    Late Binding Using Reflection

    Reflection provides a way to inspect and interact with types and their members at runtime. Using reflection, you can dynamically invoke methods, get or set properties, and even instantiate types that are not known at compile time.

    Example of Late Binding Using Reflection

    using System;
    using System.Reflection;
    
    public class Person
    {
        public string Name { get; set; }
    
        public void PrintName()
        {
            Console.WriteLine("Name: " + Name);
        }
    }
    
    public class Program
    {
        public static void Main()
        {
            // Create an instance of Person using reflection
            Type personType = typeof(Person);
            object personInstance = Activator.CreateInstance(personType);
    
            // Set the 'Name' property using reflection
            PropertyInfo nameProperty = personType.GetProperty("Name");
            nameProperty.SetValue(personInstance, "John Doe");
    
            // Call the 'PrintName' method using reflection
            MethodInfo printNameMethod = personType.GetMethod("PrintName");
            printNameMethod.Invoke(personInstance, null);  // Invoke without parameters
        }
    }
    

    Key Points:

    • Activator.CreateInstance: Used to create an instance of Person dynamically.
    • GetProperty and GetMethod: Used to obtain information about the Name property and the PrintName method.
    • SetValue and Invoke: Used to set the property value and invoke the method dynamically.

    Reflection can be more powerful than dynamic in some scenarios, as it allows access to private members, more fine-grained control over method invocation, and the ability to examine assemblies.


    Performance Considerations

    While late binding offers significant flexibility, it comes at a performance cost:

    1. Reflection and dynamic invoke methods or access properties at runtime, which is slower than compile-time checking (early binding).
    2. Errors with late binding (such as missing methods or properties) are caught at runtime rather than at compile time, which makes debugging more difficult.

    It's generally best to use late binding only when necessary, such as when working with COM objects, interacting with dynamically loaded assemblies, or when the type of an object is unknown at compile time.


    Use Cases for Late Binding

    1. Interoperating with COM objects: When you work with COM components, their methods and properties are not known at compile time. Late binding is used to interact with COM objects dynamically.

    2. Plug-in architectures: In systems where you load assemblies or types dynamically (such as a plugin system), late binding can be useful for invoking methods on objects that are unknown at compile time.

    3. Serialization/Deserialization: When you deserialize data (like JSON or XML) into objects, the types may not be known at compile time. Late binding can be used to manipulate these objects once they're deserialized.

    4. Dynamic Object Interaction: Sometimes, you may not know the structure of an object in advance, such as when working with objects received from external APIs or user input. The dynamic keyword allows you to interact with such objects without prior knowledge of their type.


    Conclusion

    Late binding in C# provides the ability to work with objects, methods, and properties whose types and members are determined at runtime. Using the dynamic keyword or reflection, you can invoke methods or access members dynamically, making your application more flexible. However, while this flexibility is useful, it comes with performance costs and potential runtime errors, so it should be used judiciously.

    Previous topic 28
    Reflection
    Next topic 30
    Directories and Files

    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 time6 min
      Word count999
      Code examples0
      DifficultyIntermediate