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›Using References
    Advanced ProgrammingTopic 19 of 55

    Using References

    8 minread
    1,277words
    Intermediatelevel

    Using References in C#

    In C#, references are a way to link one project or assembly (such as a class library) to another. This allows you to use the functionality and types defined in another project or library in your current project. Properly managing references is a key part of developing modular, maintainable, and scalable applications. C# provides several methods for adding and managing references, particularly when working with projects, external libraries, and assemblies.


    1. What Are References in C#?

    A reference in C# typically means an assembly reference or a project reference. It allows your code to access types (such as classes, interfaces, structs, etc.) defined in another project or external library. References can point to either:

    • Assemblies (DLL files): These are compiled code files that contain reusable types.
    • Project References: These allow one project to reference another project, so you can directly access its code and types.

    2. Types of References

    C# provides several ways to add references to your project:

    A. Assembly References

    An assembly reference refers to an external compiled library (DLL or EXE). These are typically added to a project to include precompiled functionality that your application requires. Assembly references are most commonly used when:

    • You want to use external libraries or .NET Framework libraries.
    • You reference DLLs that are built by other teams or third-party vendors.

    B. Project References

    A project reference connects two projects within the same solution. When one project is referenced by another, the compiler automatically uses the classes, methods, and other types defined in the referenced project. This is useful for modular development, where each project provides a specific functionality (like a class library) that is referenced by others (like a console application or a web application).

    C. NuGet Package References

    NuGet is the package manager for the .NET ecosystem. It allows you to add references to external libraries by downloading them from the NuGet repository. These packages are automatically managed by Visual Studio or the .NET CLI.


    3. Adding References in C#

    There are several ways to add references depending on whether you're using the .NET CLI, Visual Studio, or editing the project file manually.

    A. Adding a Reference Using .NET CLI

    The .NET CLI provides commands for adding references to your project.

    1. Adding a Project Reference

    If you want to reference another project within your solution, you can use the following command:

    dotnet add reference <path-to-project>.csproj
    

    Example:

    dotnet add reference ../MyClassLibrary/MyClassLibrary.csproj
    

    This command adds a reference to the MyClassLibrary project located in the parent directory.

    2. Adding an Assembly Reference

    If you have a compiled DLL file that you want to reference, use the dotnet add reference command with the path to the DLL file:

    dotnet add reference <path-to-dll>\MyClassLibrary.dll
    

    Example:

    dotnet add reference ./libs/MyClassLibrary.dll
    

    3. Adding a NuGet Package Reference

    To add a NuGet package reference, you can use the following command:

    dotnet add package <package-name>
    

    Example:

    dotnet add package Newtonsoft.Json
    

    This command adds the Newtonsoft.Json package to your project, allowing you to use JSON parsing and serialization functionality.

    B. Adding a Reference in Visual Studio

    Visual Studio provides a graphical interface for managing references, making it easy to add references to projects, assemblies, and NuGet packages.

    1. Adding a Project Reference in Visual Studio

    1. Right-click on your project in the Solution Explorer and select Add > Reference.
    2. In the Reference Manager dialog, select Projects from the left-hand menu.
    3. Check the box next to the project you want to reference.
    4. Click OK.

    2. Adding an Assembly Reference in Visual Studio

    1. Right-click on your project in the Solution Explorer and select Add > Reference.
    2. In the Reference Manager, choose Assemblies > Framework or Assemblies > Extensions.
    3. Select the DLLs or assemblies you want to reference.
    4. Click OK.

    3. Adding a NuGet Package Reference in Visual Studio

    1. Right-click on your project in the Solution Explorer and select Manage NuGet Packages.
    2. In the NuGet Package Manager, search for the package you want to install.
    3. Click Install to add the package to your project.

    4. Using References in Code

    Once references are added to your project, you can begin using the types and functionality from the referenced assemblies or projects.

    Example 1: Using a Class Library Reference

    Let's say you have a project (MyConsoleApp) that references a class library (MyClassLibrary), and the class library contains a class called MyClass with a method SayHello():

    using MyClassLibrary;
    
    class Program
    {
        static void Main()
        {
            MyClass myClass = new MyClass();
            Console.WriteLine(myClass.SayHello());
        }
    }
    

    In this example, the MyConsoleApp project uses the SayHello method from the MyClassLibrary class by referencing the library. You can use classes and methods from the referenced class library just like any other type in your project.

    Example 2: Using a NuGet Package Reference

    If you add a NuGet package, such as Newtonsoft.Json (a popular JSON library), to your project, you can use its functionality like so:

    using Newtonsoft.Json;
    
    class Program
    {
        static void Main()
        {
            var jsonObject = new { Name = "John", Age = 30 };
            string jsonString = JsonConvert.SerializeObject(jsonObject);
            Console.WriteLine(jsonString);
        }
    }
    

    In this example, the JsonConvert.SerializeObject() method from Newtonsoft.Json is used to convert an object into a JSON string.


    5. Managing References in the .csproj File

    The project file (.csproj) defines the references used by your project. It includes information about the referenced assemblies, projects, or NuGet packages.

    Here’s an example of what the .csproj file might look like with various types of references:

    Example of .csproj File

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
      </PropertyGroup>
    
      <!-- Project reference to another project -->
      <ItemGroup>
        <ProjectReference Include="..\MyClassLibrary\MyClassLibrary.csproj" />
      </ItemGroup>
    
      <!-- Assembly reference to a DLL -->
      <ItemGroup>
        <Reference Include="MyClassLibrary">
          <HintPath>..\libs\MyClassLibrary.dll</HintPath>
        </Reference>
      </ItemGroup>
    
      <!-- NuGet package reference -->
      <ItemGroup>
        <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
      </ItemGroup>
    
    </Project>
    
    • ProjectReference: A reference to another project in the solution.
    • Reference: A reference to an external DLL, where <HintPath> specifies the location of the DLL.
    • PackageReference: A reference to a NuGet package, specifying the package name and version.

    6. Removing References

    You may want to remove a reference when it is no longer needed. You can do this either through the .NET CLI or Visual Studio:

    A. Using .NET CLI

    To remove a reference from the project, use the dotnet remove command:

    dotnet remove reference <path-to-project>.csproj
    

    Example:

    dotnet remove reference ../MyClassLibrary/MyClassLibrary.csproj
    

    For NuGet packages:

    dotnet remove package <package-name>
    

    Example:

    dotnet remove package Newtonsoft.Json
    

    B. Using Visual Studio

    1. In Solution Explorer, right-click the References node.
    2. Select Manage NuGet Packages or Add/Remove References.
    3. Uncheck the reference or package you want to remove.
    4. Click OK.

    7. Summary

    References in C# allow your project to access types and functionality from other assemblies, class libraries, or NuGet packages. You can add references to your project using the .NET CLI, Visual Studio, or by manually editing the .csproj file.

    Key Points:

    • Project References: Link to another project in the same solution.
    • Assembly References: Link to external DLLs or assemblies.
    • NuGet References: Link to external libraries downloaded from NuGet.org.
    • Managing References: You can manage references using the .NET CLI or Visual Studio.
    • Removing References: You can remove references when they are no longer needed.

    By properly managing references, you can build modular, maintainable, and reusable code across multiple projects.

    Previous topic 18
    Class Libraries
    Next topic 20
    Assemblies

    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,277
      Code examples0
      DifficultyIntermediate