7

I'm (very) new to C#, and I need to know how to import classes.

In Java, I could just say:

package com.test;
class Test {}

And then in some other class:

package com.test2;
import com.test.Test;

How could I do this in C#?

Lucas Baizer
  • 169
  • 1
  • 2
  • 10
  • 2
    In C# you import namespaces, not classes. If the class you are working in is in the same namespace, you don't need to do anything. If its in a different namespace and you are using Visual Studio, just type the name of the class and use the smart tag drop down to add the appropriate `using` to the top of the class file. See the existing `using` statements for how to include namespaces. – Ron Beyer Jul 09 '15 at 17:31
  • possible duplicate of [Using a class file/reference it?](http://stackoverflow.com/questions/3599722/using-a-class-file-reference-it) – Jashaszun Jul 09 '15 at 17:31
  • @Jashaszun I don't understand that, sorry. It's probably really, really simple and I'm just too stupid to figure it out. – Lucas Baizer Jul 09 '15 at 17:36
  • Grab CLR via C#, skip the first two chapters, and read. It'll take you an afternoon and you'll be 1000% better off for it. –  Jul 09 '15 at 17:36
  • @Will Thanks. Will do. – Lucas Baizer Jul 09 '15 at 17:42

2 Answers2

15

Importing namespaces is accomplished in C# with the using directive:

using com.test;

However, there is no way, currently, to import a class. Importing classes, however is a new feature which is being introduced in C# 6 (which will come with Visual Studio 2015).

In C#, namespaces are the semi-equivalent of Java's packages. To declare the namespace, you just need to do something like this:

namespace com.test
{
    class Test {}
}

If the class is declared in a separate assembly (such as a class library), simply adding the using directive is not enough. You must also add a reference to the other assembly.

Steven Doggart
  • 42,597
  • 8
  • 69
  • 103
-1

I don't come from a Java background, but I come from a Python, C/C++ background where I always used something like "import" or "#include" and it always felt pretty simple.

But I want to share what I have learned so that others after me don't have to go through the same confusion. To give an example, I am going to show how to create a SHA256 instance.

using System.Security.Cryptography; //this is the namespace, which is what you import; this will be near the top of documentation you read
using static System.Security.Cryptography.SHA256; //this is an additional class inside the namespace that you can use; this will be in the "derived" section of documentation

AlgorithmHash sha = SHA256.Create(); //I am not entirely sure why, but the declaration needs to be on the same line as the instantiation

I have attached the HashAlgorithm documentation for reference: https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.hashalgorithm?view=net-5.0.

Alaska
  • 151
  • 8