Home > database >  How to split C# (Console application) classes into different files
How to split C# (Console application) classes into different files

Time:06-15

namespace APIproject    
{

    public class ApiCallResponse //class1

    class Program //class2
}

I have two classes in my code and both are in the same file name Program.cs. I want to shift my ApiCallResponse class into another file like Program1.cs And then I want to call the new file Program1.cs into Program.cs to access that class. How can I do that?

CodePudding user response:

If you want to have a class in a separate file, which is actually a common practice, you need to add a class file (*.cs) and write your code there.

After this, you need to reference a namespace that contains your class and then use your class as usual:

Program.cs:

using MySolution.Responses; //This is how you can connect different classes.

namespace MySolution
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var response = new ApiCallResponse();
        }
    }
}

../Responses/ApiCallResponse.cs:

namespace MySolution.Responses
{
    public class ApiCallResponse
    {
        public ApiCallResponse()
        {
            
        }
    }
}

  • Related