How to Import Old code from a Different namespace into My Current Project?

Viewed 41

I want to use old code in a new project in c#.

This is the old code. It is saved in an arbitrary folder on my PC.

namespace OldCode{
    class HellowWorld
    {
        public static void SayHello()
        {
            Console.writeline("Hello World")
        }
    }
}

I want to use this in a new project called new code.

using OldCode (?)

namespace NewCode
{
    class SayHelloNew
    {
        HelloWorld.SayHello();
    }
}

My question is, how do I link to my old project? Did I do it right with using OldCode? Or is there some other dependency file I need to set up?

2 Answers

That is almost correct. The colon (:) needs to be removed from the namespace declaration and to access the HelloWorld class externally, it must be public.

OldCode\HelloWorld.cs

namespace OldCode
{
    public class HelloWorld
    {
        public static void SayHello()
        {
            Console.writeline("Hello World")
        }
    }
}

NewCode\SayHelloNew.cs

using OldCode;

namespace NewCode
{
    class SayHelloNew
    {
        HelloWorld.SayHello();
    }
}

You will also need to ensure the compiler has access to OldCode on compilation, or, if using Visual Studio, add a Reference to the OldCode project in the NewCode project.

Add references in Visual Studio

Yeap, Let me describe for you,
First you should make public your class to access it in other sources by adding public modifier like this:

using System;
namespace Stackoverflow.OldCode
{
    public class HelloWorld    // <----------- make it public
    {
        public static void SayHello()
        {
            Console.WriteLine("Hello World!!!");
        }
    }
}

Then I suggest adding a prefix in every other namespaces to show they are related to each other, like

namespace Stackoverflow.OldCode;
namespace Stackoverflow.NewCode;

The NewCode project and the OldCode should be in one solution, if not now, right-click on the solution name and choose: Add>New Project... or Add>Existing Project...

add new project

Then you should add the NewCode project as a reference to the OldCode project:

step1:

add refrence step2:

choose the old proj

Now you can access old project methods easily, like:

using Stackoverflow.OldCode;   // <---- add the reference
namespace Stackoverflow.NewCode
{
    class SayHelloNew
    {
        public static void SomeRandomName()
        {
            HelloWorld.SayHello();  // <----- call it 
        }
    }
}
Related