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#?
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#?
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.
IDisposable
pattern. This is called a using directive. –
Invitatory 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://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.hashalgorithm?view=net-5.0.
© 2022 - 2024 — McMap. All rights reserved.
using
to the top of the class file. See the existingusing
statements for how to include namespaces. – Haggai