Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C#: How to call methods from class libraries and printing them into console projects?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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; 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading