I'm writing a simple C# program. I have two files, ClassA.cs
and ClassB.cs
.
Each of these files implements its respective class.
I want to create an object of ClassB inside a method of ClassA.
My code looks like this:
ClassA.cs
using System;
public class ClassA {
public static void Main(string[] args) {
Console.WriteLine("Starting...");
ClassA classA = new ClassA();
}
public ClassA() {
ClassB classB = new ClassB();
}
}
ClassB.cs
using System;
public class ClassB {
public ClassB()
{
Console.WriteLine("ClassB created.");
}
}
How can I compile this project now? When I try to do csc ClassA.cs ClassB.cs
I get the error The type or namespace name 'ClassB' could not be found
.
I'm guessing I'm missing something like an import
statement from Java or include
from C++. What's the equivalent in C#?
Also, I'm not using an IDE. Only writing the files in a text editor and manually compiling / running in the console (windows).
I created 2 files in the same folder ( c:\\code\\egcsc
): ClassA.cs
and ClassB.cs
, with the respective contents you have shown.
Then:
c:\code\egcsc>dir
Volume in drive C is (irrelevant)
Volume Serial Number is (irrelevant)
Directory of c:\code\egcsc
28/03/2018 12:26 <DIR> .
28/03/2018 12:26 <DIR> ..
28/03/2018 12:24 253 ClassA.cs
28/03/2018 12:25 126 ClassB.cs
2 File(s) 379 bytes
2 Dir(s) (irrelevant) bytes free
c:\code\egcsc>csc ClassA.cs ClassB.cs
Microsoft (R) Visual C# Compiler version 2.8.0.62716 (e205ae18)
Copyright (C) Microsoft Corporation. All rights reserved.
c:\code\egcsc>ClassA.exe
Starting...
ClassB created.
So; it worked fine; you need to double-check what you have. Note: using a tool like VSCode or Visual Studio (there are free versions) would make this a lot easier...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.