When I am trying to call a method of another project class file, I am getting the following error
I have 2 C# library projects inside same solution file.
Inside each project I have a class file.
I have added reference of one project inside other.
There are NO compile time or build errors.
During runtime, it is throwing the following exception (Image attached above)
My question is, how does one able to call a class method of one project from another method ?
Thanks in advance :)
Is your current project class file exist in the actual directory? The physical file might not be on the disk itself so it has this error message.
Simply put if your physical file exist in your directory, and if you wanna call that method in, be sure to put the namespace at the top and import that reference from your solution explorer.
Also, Do remember to include your method class as public.
Example Below:
public class GetUserDetails
{
//methods
}
First check the target framework and verify that the two C# library projects have the same framework.
Did you miss deploying or referencing any assembly (DatabaseUtil.dll) in the old version?
Check to make sure that the referenced assembly exists in your bin folder. If it does exist, check if it is 32-bit or 64-bit.
Go to References in Solution Explorer in Visual Studio. Select the assembly which is getting complained.
Set its Copy Local to true in its Properties page.
And I suggest you try the suggestions in this thread.
If the above methods are not successful, please provide the relevant code to reproduce the problem.
Daniel Zhang
I get this strange thing when I create a new class, Next to the namespace name I get a .Classes which all I can tell prevents me from creating an instance of the class and hides it.
I would include the screen shot but im not sure how I do this. Please help so you can better understand the question.
Thanks
The namespace within Visual Studio will depend on two things:
The default namespace defined within the project properties.
The folder structure within your project.
I think that within your project you have a folder Classes where you put (well as the name guesses) your classes. Due to this fact Visual Studio will automatically append this name to the default namespace.
So either manually change the namespace manually right after you added a new class or move the file one level up within your folder structure of the project.
Steps to reproduce:
Create a new C# console project.
Write some code:
class Foo { }
class Bar
{
Foo x;
}
Observe that in Foo x; the class name is highlighted. Intellisense will work for classes in this assembly.
Edit the .csproj file to include "**\*.cs" instead of "Program.cs", to include all .cs files in the project directory and its subdirectories.
Reload the project when prompted.
Observe that the C# file is still loaded and part of the project, but that Intellisense and syntax highlighting no longer recognise any types declared in this assembly or in 3rd party assemblies that are not installed in the GAC.
Why does this happen? I would like to use wildcards to make it easier to add new files outside of the Visual Studio IDE.
I still don't know why this happens, but I did find out how to fix it: replace **\*.cs with .\**\*.cs and as if by magic, it all works. Hope that helps somebody else!
In the same solution, I have two projects: P1 and P2. How can I make use of a class of P1 in P2?
In the 'Solution Explorer' tree, expand the P2 project, right-click (Shift+F10) the 'Dependencies' node and select 'Add Project Reference...'.
On the 'Add Reference' dialog, select your P1 project.
If you are using namespaces then you will need to import the namespaces for your P1 types by adding 'using' statements to your files in P2.
Note that the types in P1 that you wish to access directly must have a sufficient access level: typically this means they must be made public.
Note: If you are working on an older project (e.g. .NET Framework) you may not have the 'Dependencies' node. In which case right-click the project and select 'Add Reference' from the menu and then ensure the 'Projects' tab is selected on the left.
Simply add reference to P1 from P2
Paul Ruane is correct, I have just tried myself building the project.
I just made a whole SLN to test if it worked.
I made this in VC# VS2008
<< ( Just helping other people that read this aswell with () comments )
Step1:
Make solution called DoubleProject
Step2:
Make Project in solution named DoubleProjectTwo (to do this select the solution file, right click --> Add --> New Project)
I now have two project in the same solution
Step3:
As Paul Ruane stated. go to references in the solution explorer (if closed it's in the view tab of the compiler). DoubleProjectTwo is the one needing functions/methods of DoubleProject so in DoubleProjectTwo right mouse reference there --> Add --> Projects --> DoubleProject.
Step4:
Include the directive for the
namespace:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DoubleProject; <------------------------------------------
namespace DoubleProjectTwo
{
class ClassB
{
public string textB = "I am in Class B Project Two";
ClassA classA = new ClassA();
public void read()
{
textB = classA.read();
}
}
}
Step5:
Make something show me proof of
results:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DoubleProject
{
public class ClassA //<---------- PUBLIC class
{
private const string textA = "I am in Class A Project One";
public string read()
{
return textA;
}
}
}
The main
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DoubleProjectTwo; //<----- to use ClassB in the main
namespace DoubleProject
{
class Program
{
static void Main(string[] args)
{
ClassB foo = new ClassB();
Console.WriteLine(foo.textB);
Console.ReadLine();
}
}
}
That SHOULD do the trick
Hope this helps
EDIT::: whoops forgot the method call to actually change the string , don't do the same :)
All too often a new developer asks this simple question which is a common problem specifically with Visual Studio IDE's. Few people answer the specific question and often critique the question or give "guesses" for solutions which don't answer the common problems. The first common problem is the IDE leads you to create new projects rather than add new files (.java, .py, .cpp, .c) to the existing solution (by default it creates a new solution) unless you change the project name and add to the current solution. This problem occurs for Python, java, c#, C++ and C project folders.
The new developer selecting "new>project>project name and changing the solution directory to "use same solution" still creates a new "project" in the same solution space, but not in the same directory space as the current user interface file or command line file which still leads to problems with "package not found" errors when building and running the project or solution. This is why the above coding suggestions to importing packages, classes, methods and functions only work (and thus don't answer the question) when the "library" file or "separate behavior" file is not only in the same solution directory path, but also in the same "user interface" or "command shell" application directory space. This does does not happen when you add another project using the new>project>project type commands of the IDE. The problem here is the new project is stored in a different directory than the existing Client or User interface code files. To create a new "file" in the same project space rather than new project the beginner needs to do the following that Microsoft won't do for you and even misleads you away from the intuitively obvious by default.
Select the "application" you want to import the new behavior into (from another file)
Select project>add new item
Select the "program file template type" such as filetype.py, filetype.java, filetype.c, filetype.cpp, filetype.C#, etc. or a library class file type (something other than startup file options you see when you create a new application project or create a new library project).
A new file name with default name is created in your project.
Change the default name of the file to something like library.py or façade.java, etc.
NOW the code recommendations to import libraries or using namespaces will work as described in the comments above and you don't have to change path statements or change solutions paths and solution names that Microsoft won't let you change easily (i.e. you can change the filenames or project names but the IDE won't automatically change the project path or the solution path names).
The following is a Python example but works similar for C#, java, or C/C++ using the includes, namespaces or using code commands appropriate to each language to find code in other classes/projects in the SAME DIRECTORY SPACE.
The application file "hello world" importing from other code files in the same directory.
Note the python white space delimiters are not going to space correctly in this stackoverflow comment editor:
print ("test")
from CIXMPythonFacade import ClassA
c1=ClassA
c1.methodA()
from CIXMPythonFacade import functionA
functionA()
class ClassName(object):
def __init__(object, parameter):
object.parameter = value
The library file or "façade" file containing classes, methods or functions you want to import.
class class1(object):
"""description of class"""
class ClassA(object):
print ("test2")
def methodA():
print ("test3")
def functionA ():
print ("test4")
return (0)
pass
NOW how do you actually solve the mess that the IDE leads you into? To import code from another file in the same directory space you add a reference to it.
Select the application file
Select Project>add reference
Choose the filename visible with the right directory path (check it)
The reference is now available to the interpreter, the code checker and/or the compiler.
OK so now that you have this problem solved, how do you really link two separate projects together in the same solution space?
You have to go to both the indexer or "intellisense" options and the compiler/interpreter and physically check or change/add the directory path statements if they are something other than what points to your "second" project or solution space. When you do the path changes or change the path variables to your workspace and to the specific locations of the projects which are different directory spaces the compiler and the code analyzer can then find these libraries, headers.h, namespaces, project or file locations.
To remove old projects you created by mistake it is even worse. You have to exit the Visual Studio IDE, open windows explorer, go to the workspace directory ...documents\visualstudio xxx\solutionname\packagename
select the file or folder, right click and "delete" file or folder.
When you re-enter the IDE and select open solution or open package/solution, the old files and solution/package names are gone as are their misleading path statements which fools the compiler and code analyzer to look at the old directory even though you changed the filename and changed the project name, it does not change the directory path with it.
Microsoft really, really needs to fix these problem so you can intuitively create what most people want to create as new files in the same directories and remove solutions by selecting them and deleting them from the IDE. Beginners get so frustrated with directory path statements so flexible for seasoned developers, but so unfair to new developers in their defaults.
Hope this really helps you new guys and stops seasoned developers from giving you the wrong answers that don't work for you. They assume you already understand path statements and just want to type the right code...which is also why the tunnel in on trying to correct your code but does not help you fix the problem. This is probably the most common problem continually described on stackoverflow with wrong answers that don't work for new programmers.
The first step is to make P2 reference P1 by doing the following
Right Click on the project and select "Add Reference"
Go to the Projects Tab
Select P1 and hit OK
Next you'll need to make sure that the classes in P1 are accessible to P2. The easiest way is to make them public.
public class MyType { ... }
Now you should be able to use them in P2 via their fully qualified name. Assuming the namespace of P1 is Project1 then the following would work
Project1.MyType obj = new Project1.MyType();
The preferred way though is to add a using for Project1 so you can use the types without qualification
using Project1;
...
public void Example() {
MyType obj = new MyType();
}
If you have two projects in one solution folder.Just add the Reference of the Project into another.using the Namespace you can get the classes. While Creating the object for that the requried class. Call the Method which you want.
FirstProject:
class FirstClass()
{
public string Name()
{
return "James";
}
}
Here add reference to the Second Project
SecondProject:
class SeccondClass
{
FirstProject.FirstClass obj=new FirstProject.FirstClass();
obj.Name();
}
In project P1 make the class public (if it isn't already). Then add a project reference (rather than a file reference, a mistake I've come across occasionally) to P2. Add a using statement in P2 at the correct place and start using the class from P1.
(To mention this: The alternative to making the class public would be to make P2 a friend to P1. This is, however, unlikely to be the answer you are after as it would have some consequences. So stick with the above suggestion.)
Say your class in project 2 is called MyClass.
Obviously, first reference your project 2 under references in project 1 then
using namespaceOfProject2;
// for the class calling bit:
namespaceOfProject2.MyClass project2Class = new namespaceOfProject2.MyClass();
so whenever you want to reference that class you type project2Class. Plus make sure that class is public too.
I had an issue with different target frameworks.
I was doing everything right, but just couldn't use the reference in P2.
After I set the same target framework for P1 and P2, it worked like a charm.
Hope it will help someone
You will need to right click your project and select add -> Reference... -> Projects and tick the project you would like to reference.
The result of this should show the referenced project under the references section of your project tree.
A common use case involves adding a testing framework, say, a NUnit project to your solution. This NUnit project would then need to reference your main project. In order to do this, the steps are slightly different:
You will need to right click your NUnit project and select add -> Project Reference... -> Projects and tick the project you would like to reference.
The result of this should show the referenced project under the "Projects" section of your NUnit project tree.
To provide another much simpler solution:-
Within the project, right click and select "Add -> Existing"
Navigate to the class file in the adjacent project.
The Add button is also a dropdown, click the dropdown and select
"Add as link"
Thats it.
I want to force a root namespace on the contents of any .cs source files that don't have their contents wrapped in an explicit namespace. In other words I want to keep classes and other namespace-level structures out of the default namespace.
(Working inside a Windows .NET environment with Visual Studio)
In the following example, I want to force the Car class into the MotorIndustry namespace by default even though it has no explicit namespace coded.
Vehicle.cs (has namespace)
namespace MotorIndustry {
public class Vehicle {
// ...
}
}
Car.cs (no namespace/default)
public class Car : Vehicle {
//...
}
Is there a way to accomplish this "root namespace" modification behaviour through project settings in Visual Studio, AssemblyInfo.cs file or some other means?
My understanding is VB.NET has a feature like this but C# acts differently?
Some context about why am I asking this: I have hundreds of classes and the programmer forgot to wrap the namespace around some. When I reference the assembly from other projects it's polluting the default namespace with classes that end up causing some ambiguous situations.
Use ReSharper to move the classes into the proper namespace. In fact, version 5.0 (still in Beta) allows you to correct namespaces globally.
The other way to do it is to make the other developer fix the code.
It sounds like you are trying to replicate VB.Net's project namespace feature in C#. This is not a supported feature of the C# compiler or IDE. You will not be able to create one by modifying a project file. You will need to add the namespace to every file in the project either manually or via a tool.