I am confused on how to use a namespace. I understand that a namespace is a way to group a variety of different classes into one section. My problem is I don't understand how to use such a namespace.
For example lets say I create
using System;
namespace MyMath
{
static class MyOperations
{
public static int MyAdd(int x, int y)
{
return x + y;
}
}
}
This is created in a seperate project in C#.
Now what if I want to use this namespace in a different project to use my method how do I go about doing that?
using System;
using MyMath;
namespace Test
{
class Program
{
static void Main(string[] args)
{
int sum = MyOperations.Add(5, 10);
}
}
}
This will give me an error. I don't understand where I put the Program.cs of the MyMath project to make it useable in the other project.
There are two things you have to do:
MyOperations
class should have a public
access modifier. Right now, it has internal
; that means, you can use the class only in the same assembly it is declared in. Change it to the following: public static class MyOperations
You need to add a project reference in your console project to your class library project.
See https://msdn.microsoft.com/en-us/library/f3st0d45.aspx?f=255&mspperror=-2147217396#Anchor_1
You have two options. Suppose MyMath is a Main Namespace where you will add Test Namespace
If you use different project in same Solution Explorer then you need to add source project from Add Reference->Project then select.
If you use different project in different Solution Explorer then you need to add dll of Source(Test Namespace) project from Add Reference.
We can use Test Namespace
using Test;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.