I am new to C# and I am learning how to pass values between class libraries and console apps.
Currently I have a 2 project set up in separate sub-folders. Where:
main–>lib –> classlib.cs
main–>src –>console.cs
Furthermore classlib.cs is set up like this:
namespace lib;
public class Passing
{
public int being_passed = 4;
}
While in console.cs :
using lib;
Console.Writeline(lib.Passing.being_passed.ToString());
For some reason my console.cs is not able to recognize my classlib.cs.(ie. it lists that the lib namespace has not been recognized) Even after adding a project reference in console.cs via the command dotnet add reference {path to classlib.csproj file here}.
>Solution :
You attempt to access being_passed as if it was a static field of class Passing. But it isn’t.
You need to have an instance of class Passing in order to access the non-static field being_passed:
// create an instance:
lib.Passing passingInstance = new lib.Passing();
// access the field:
Console.Writeline(passingInstance.being_passed.ToString());
Alternatively, you can make the field static in the library (and then access it the way you attempted, since a static field does not require an instance):
public class Passing
{
//--vvvvvv----------------------------
static public int being_passed = 4;
}