I'm quite new to C#, and have made a class that I would like to use in my main class. These two classes are in different files, but when I try to import one into the other with using
, cmd says says
The type or namespace name "MyClass" could not be found (are you missing a using directive or an assembly reference?
I know that in Java I have to mess around with CLASSPATH
to get things like this to work, but I have no idea about C#.
Additional details:
As you've probably figured out, I'm compiling and executing via command prompt. I'm compiling my non-main class using /target:library
(I heard that only main classes should be .exe-files).
My code looks like this:
public class MyClass {
void stuff() {
}
}
and my main class:
using System;
using MyClass;
public class MyMainClass {
static void Main() {
MyClass test = new MyClass();
/* Doesn't work */
}
}
I have tried to encompass my non-main class with namespace MyNamespace { }
and importing that, but it doesn't work either.
using
is for namespaces only - if both classes are in the same namespace just drop the using
.
You have to reference the assembly created in the first step when you compile the .exe:
csc /t:library /out:MyClass.dll MyClass.cs
csc /reference:MyClass.dll /t:exe /out:MyProgram.exe MyMainClass.cs
You can make things simpler if you just compile the files together:
csc /t:exe /out:MyProgram.exe MyMainClass.cs MyClass.cs
or
csc /t:exe /out:MyProgram.exe *.cs
EDIT: Here's how the files should look like:
MyClass.cs:
namespace MyNamespace {
public class MyClass {
void stuff() {
}
}
}
MyMainClass.cs:
using System;
namespace MyNamespace {
public class MyMainClass {
static void Main() {
MyClass test = new MyClass();
}
}
}