I am a newbie of C# and MS visual studio, and I want to use the C# class which defined in another file, but can't get it work.
Here is the program.cs
(and why can't I rename that file ?)
using System; namespace TestCSharp2 { class Program { static void Main(string[] args) { Class2 class2 = new Class2(); // here the IDE will complain that cant find namespace or balabala.. class2.setValue(10); Console.WriteLine(class2.getValue().ToString()); Console.ReadKey(); } } }
And here is the Class2
that I want to use in file Class2.cs
:
namespace TestCSharp2 { class Class2 { int i; public void setValue(int i) { this.i = i; } public int getValue() { return this.i; } } }
Should I #include
or something? isn't use namespace
enough?
As some guys asked if they are in the same assembly/same project, I presume they were, because here is the procedure how they are created:
program.cs
was created by default.program.cs
lives.To be honest, I don't know if they are in same assembly / same project, but I guess they were.
you need to forward declare the name of the class if you don't want a header: class ClassTwo; Important: This only works in some cases, see Als's answer for more information.. Forward declaring the class ClassTwo before the code statement ClassTwo ctwo; won't solve the problem.
To access, use and initialize the private data member you need to create getter and setter functions, to get and set the value of the data member. The setter function will set the value passed as argument to the private data member, and the getter function will return the value of the private data member to be used.
Composition. When a class uses object of another class this is called composition. In cases of composition it will be necessary for the class constructor to specify how constructors are called for its data members.
According to your explanation you haven't included your Class2.cs
in your project. You have just created the required Class file but haven't included that in the project.
The Class2.cs was created with [File] -> [New] -> [File] -> [C# class] and saved in the same folder where program.cs lives.
Do the following to overcome this,
Simply Right click
on your project then -> [Add] - > [Existing Item...] : Select Class2.cs
and press OK
Problem should be solved now.
Furthermore, when adding new classes use this procedure,
Right click
on project -> [Add] -> Select Required Item (ex - A class, Form etc.)
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