You are free to remove assembly references if you like, but be aware that removing a reference to an assembly required for that project type is likely to result in your code not being ab
Trang 1As you can see in Figure 5-5, the Assembly Information from the project properties
is included with the file This is convenient for you (or an end user) to be able to open the file and read pertinent information, especially version information, to know you’re working with the correct assembly, for debugging, or just to know what is on your system
Referencing Assemblies
All projects normally reference external assemblies For example, System.dll is a NET Framework assembly that contains all of the primitive NET types and is normally included in every project Each project type has a specific set of assemblies that appear in the References list The assemblies that appear in this list are either required because of the type of project you are building or are optional and contain libraries that are commonly used for that type of project You are free to remove assembly references if you like, but be aware that removing
a reference to an assembly required for that project type is likely to result in your code not being able to compile
Figure 5-5 File Properties window
Trang 2Assembly references are added to a project to tell the compiler where to find the types
it is using in an application When your compiler runs, it will know what types you have
in your code and looks through the set of referenced assemblies to find that type Adding
an assembly reference doesn’t add all of the code from the referenced assembly to your
code; it just tells the compiler where to look
NOTE
There is often confusion around the relationship between assembly references and
namespaces A namespace using statement (Imports in VB) allows your code to be
written without fully qualifying type references for types in an assembly However, the
assembly reference is just a way to tell the compiler in which specific external assembly
to look to find those types: two different purposes This confusion is exacerbated by the
fact that you get the same error message from the compiler when you either are missing
an assembly reference or don’t have a using (Imports for VB) directive in your code for
a namespace that a type resides in Just remember to ensure that you have an assembly
reference first and then add a using (Imports) directive at the top of your file.
Adding a NET Assembly Reference
You can add references to your project by right-clicking the project and clicking Add
Reference You’ll see the Add Reference window, shown in Figure 5-6 On the NET
tab of this window, you’ll see a list of assemblies from the Global Assembly Cache
Figure 5-6 The Add Reference window
Trang 3(GAC), which is a shared repository of assemblies Microsoft and third parties will place assemblies in the GAC to make it easier to share them by any programs
The COM tab shows all of the COM applications currently registered on your computer For example, if you wanted to communicate with Excel, you would click the COM tab and add a reference to the version of Microsoft Office Excel that you are working with Adding a reference to a COM object causes VS to automatically generate
a new assembly, called an Interop assembly, that has stub methods that make it easy for you to perform operations on that COM object You would need to reference the documentation for the COM object/application to determine what operations are possible, but this is a very powerful way to work with legacy applications and Microsoft Office applications that expose a COM interface
CAUTION
If you’re adding an assembly reference for a VB project, remember to open My
Projects on ProjectDemo, go to the Compile tab, click the Advanced Compile Options
button, and ensure that the Target Framework is set to NET Framework 4.0 (not
.NET Framework 4.0 Client Profile) The reason is that the class library project is
automatically set to NET Framework 4.0 and the target framework for both the
referencing and referenced assemblies must be the same.
The Recent tab has a list of references that you’ve recently added to a project, which
is a convenience based on the probability that if you added a reference to one project
in a solution, you might want to quickly add that same reference to others The Browse tab of the Add Reference window allows you to search the file system for a *.dll file to add as a reference Just remember that if you are referencing a *.dll for a project in the same solution, it would be better to use the Project tab, which manages dependencies and ensures that your project is updated if the referenced project changes File references can’t know if the external *.dll changed because the external *.dll is outside of your solution
In most cases, if you’re referencing an external *.dll, you don’t have the code, so a project reference won’t be possible The next section explains more about project references
NOTE
The New Projects window, CTRL - N , contains Office project types that can help you get
started building Microsoft Office applications.
Managing Assembly References
Occasionally, you might want to remove an assembly reference because it isn’t necessary
or because you accidentally added the wrong reference In C#, you would open the References folder, select the reference to remove, and press DELETE In VB, you would
Trang 4open the Properties window by double-clicking My Project, click the References tab,
select the reference to delete, and click Remove Figure 5-7 shows the VB References tab
VB includes additional functionality on the References tab For example, you can
click Add to add a reference You also click Unused References to remove references for
assemblies that are not being used in your code Clicking Reference Paths allows you to
specify a folder that VS will look in to find assemblies you want to reference
C# has a separate tab on the Properties window for managing Reference Paths When
VS looks for referenced assemblies, it will search the current project directory, then in
the folders identified in Reference Paths, and then in folders for the list of assemblies
specified by the Add References window
Referencing Your Own Class Libraries
There are various reasons for creating your own code libraries For example, you might
have reusable code or want to keep your code organized into separate assemblies To
do this, you would create Class Library projects, and then reference those class library
projects from other code First, let’s create a Class Library project and then create a
reference to the Class Library project from a Console application
Figure 5-7 The VB My Project References tab
Trang 5Within the SolutionDemo solution, we’ll create a new project for a class library Right-click SolutionDemo and select Add | New Project This time, select Class Library
instead of Console Application and name it ClassLibraryDemo Clicking OK will add
a new Class Library Project to your SolutionDemo Solution You will now have two projects in your solution
To use the code in the ClassLibrary project, right-click the ProjectDemo project and select Add Reference This time, select the Project tab, which will contain all of the projects that belong to the same solution Select the ClassLibraryDemo project and click
OK You’ll see the reference to ClassLibraryDemo appear in the References folder in the ProjectDemo project
TIP
Resetting References for Renamed Projects You can rename any project by
right-clicking the project and selecting Rename However, that doesn’t change the physical
folder name If you want to change the physical folder name, close the solution (select
File | Close Solution) and then change the project folder name When you re-open the
solution, Solution Explorer won’t be able to load the project This is because the folder
name for the project in the solution file hasn’t changed To fix this, select the project in
Solution Explorer and open the properties window In the properties window, select the
file path property and either type the newly changed path or click the ellipses button to
navigate to the *.csproj file Navigate back to Solution Explorer, right-click the project
that didn’t load, and select Reload Project.
Now that you have a reference to a class library, you’ll want to write code that uses the objects in the class library, which you’ll learn about next
Using Code in Class Libraries
To use class library code, you need to ensure you have a reference to the class library
If using C#, you can add a using directive, and in VB you can add an Imports directive, which allows you to use the types in the class library without fully qualifying them After referencing the class library assembly and ensuring namespaces are managed properly, you can use class library classes and instantiate these externally referenced objects and access or invoke the members as if they were part of the code in your own assembly The NET CLR will take care of making sure that your calls to the class library object work transparently behind the scenes The preceding section showed you how to create the reference from one project to another, allowing the compiler to find the other assembly This section will explain how to write the code that specifies which objects in the class library to use
Assuming that you were building an educational application, you might have a class library that helped you keep track of students To facilitate this scenario, you can rename the Class1.cs or Class1.vb file in the ClassLibraryDemo project to Student.cs or Student.vb
Trang 6If you’re using C# when you do this, VS will ask if you want to change the class filename
from Class1 to Student VB will make the class name change automatically, without
asking This is a convenient way to keep your classes and filenames in sync It is common
to create only one class per file Listing 5-1 shows the new student file after renaming and
adding code to make it functional
Listing 5-1 Class library code
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClassLibraryDemo
{
public class Student
{
public List<int> GetStudentGrades(string studentName)
{
return new List<int> { 80, 100, 95 };
}
}
}
VB:
Public Class Student
Public Function GetStudentGrades(ByVal studenName As String) As
List(Of Integer)
Dim intList As New List(Of Integer)
intList.Add(80)
intList.Add(100)
intList.Add(95)
Return intList
End Function
End Class
The important parts of Listing 5-1, for the current discussion, is that Student is a class
inside of the ClassLibraryDemo namespace You’ll need to remember the namespace so
that you can obtain a reference to a Student instance from the calling code Listing 5-2
shows how Remember that the VB namespace is implicitly set to whatever is defined as
the namespace setting on the My Project page, which defaults to the project name
Trang 7Listing 5-2 Application code calling class library code
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClassLibraryDemo;
namespace ProjectDemo
{
class Program
{
static void Main(string[] args)
{
string studentName = "Joe";
Student myStudent = new Student();
List<int> grades = myStudent.GetStudentGrades(studentName); Console.WriteLine("Grades for {0}:", studentName);
foreach (int grade in grades)
{
Console.WriteLine(" - " + grade);
}
Console.ReadKey();
}
}
}
VB:
Imports ClassLibraryDemoVB
Module Module1
Sub Main()
Dim grades As List(Of Integer)
Dim studentName As String = "Joe"
Dim myStudent As New Student
grades = myStudent.GetStudentGrades(studentName)
Console.WriteLine("Grades for {0}:", studentName)
Trang 8For Each grade In grades
Console.WriteLine(" - " & grade)
Next
Console.ReadKey()
End Sub
End Module
One item to draw your attention to in Listing 5-2 is the using directive (Imports in VB), specifying that you can use the types in the ClassLibraryDemo namespace without fully
qualifying them After that, you can see how Listing 5-2 creates instances of Student and
myStudent and calls GetStudentGrades.
TIP
The call to Console.ReadKey in Listing 5-2 causes program execution to stop until the
user presses a key on their keyboard If Console.ReadKey was not present, the program
would finish the Main method, which would close the application before you had the
chance to see the output.
Next, you’ll want to compile the code to see if the syntax is good and then run the
program to see if it operates properly The next section explains how compiling and
running works with VS
Compiling Applications
You’ll find several compilation options on the Build menu Because there are so many
options, it isn’t always intuitive which option you should use The options are scoped to
either the current project or the entire solution The top portion of the menu applies to
the entire solution, and the second section is context-sensitive, applying to the currently
selected project The following sections describe each set of options, including build,
rebuild, and clean for both projects and solutions
Building Solutions/Projects
Building typically means that you run the compiler to compile source code files Sometimes
the build includes more than compilation For example, if you are writing ASP.NET
applications, VS will generate code based on the Web controls on the page and then that
generated code will be compiled with normal code Therefore, the term build is more
accurate than compile
During a normal build, VS will only build the items in a project or solution that are out
of date More specifically, only projects that have changes and edits will be rebuilt,