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.
UPDATE: As of C# 6, if you want to use the static members of a class without specifying the class name, you can use the using static directive to import the static members into the current scope, like this:
using static MyNamespace.MyClass;
Although this is not what the original question is about, you get a similar error to the one OP gets, so I'm providing it for completeness.
Answer to OP's question:
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(); } } }
I know this is very old question but I had the same requirement and just discovered that after c#6 you can use static in using for classes to import.
I hope this helps someone....
using static yourNameSpace.YourClass;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With