Link to home
Start Free TrialLog in
Avatar of Skale
Skale

asked on

How to access a project methods from another project in same solution in C#

Hello,

I have a two projects Project1 and Project 2 in same solution.

I'd like to use some functions from Project2 but i couldn't do it without defining a static field.
Is it normal? or How can i achieve this. Any help would be great to define it properly.

PS: I added Project2 to Project1's reference.

Project1's sample class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project1
{
   public class HelloFromProject1
    {

        public void SayHello()
        {

			// Calling method from another project here
			Project2.HelloFromProject2.SayHello();

        }


    }
}

Open in new window


This is Project2's sample class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project2
{
   public class HelloFromProject2
    {

        public void SayHello()
        {

            Console.WriteLine("Hello From Project 2");

        }


    }
}

Open in new window

Avatar of Chinmay Patel
Chinmay Patel
Flag of India image

Hi Hakan,

Just make sure the class you are trying to access is marked Public (Static will do, but I don't recommend it unless there is a solid reason to use Static).

Regards,
Chinmay.
Avatar of Skale
Skale

ASKER

Hi Chinmay,

It's like on example i'm using public keyword on classes
Sorry I didn't catch that.
As such now all you need is to instantiate class (Not Static classes must be instantiated)...

HelloFromProject2 pj2 = new HelloFromProject2();
pj2.SayHello();

Open in new window


If you don't need to keep the pj2 for further usage then
new HelloFromProject2().SayHello()

Open in new window


Regards,
Chinmay.
Avatar of Skale

ASKER

Thanks :) Also you mentioned you dont want to use static why? What's the disadvantages?
ASKER CERTIFIED SOLUTION
Avatar of Chinmay Patel
Chinmay Patel
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>I'd like to use some functions from Project2 but i couldn't do it without defining a static field.
Is it normal?

Just in case you haven't noticed.  The code is identical to that you would use for another class inside the same project (using the namespace within the same project is implied - you could specify it if you wished).