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.
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.
Related
I have just looked in my regedit and found I am running .NET Version 4.5.1 and therefore the libraries I am after should be available to me.
I try to include the namespaces:
using System.IO.MemoryStream;
using System.Media.SoundPlayer;
However VS complains that the namespaces do not exist.
The reference pages for MemoryStream and SoundPlayer dictate that these should be available in my version of .NET. How can I fix this?
You are confusing class names and namespaces and possibly the using directive with the using statement.
System.IO is a namespace. It's a grouping construct used to logically group classes and structs together and avoid name clashes. System.IO.MemoryStream is a class inside the System.IO namespace.
If you want to use a MemoryStream you can either:
var ms = new System.IO.MemoryStream(...);
Or, to avoid the verbosity of always specifying the namespace (a full qualified name), you can use the using directive:
using System.IO;
and then you can just use the class name:
var ms = new MemoryStream(...);
You can think of the using directive as telling the compiler what search paths to use when looking for a class. If you ask for MemoryStream it's going to first look in the current namespace for a class named MemoryStream, if it doesn't find one, it's then going to look in all the namespaces that have been imported with the using directive (in VB.NET, I believe the equivalent directive is actually called Imports which, arguably, makes more sense, but there you go). If it still doesn't find a MemoryStream class you'll get a compile time error.
Note: you'll also get a compile time error if it finds more than one MemoryStream because it won't stop on the first one - your classes need to be unambiguous. And this is a reason not to just stuff a lot of unneeded using directives at the top of every .cs file. MemoryStream isn't particularly a problem here (I think it's the only MemoryStream in the BCL), but another class in System.IO is Path. There are several classes called Path in the BCL (There is another one under System.Windows.Shapes) and without namespaces they'd be a nightmare to use.
Now, your confusion might come from the using statement which is often used with classes what implement IDisposable to ensure they get disposed. MemoryStream implement IDisposable so you'll often see things like:
using (var ms = new MemoryStream(...))
{
// some code here
}
Or, if they haven't used the using directive to declare the namespace:
using (var ms = new System.IO.MemoryStream(...))
{
// some code here.
}
Which looks a lot like what you were trying to do with your using directive.
When looking at a class in MSDN there are two important things you need to look for:
Namespace: System.IO
Assemblies: mscorlib (in mscorlib.dll)
System.IO (in System.IO.dll)
Namespace tells you what you need to include either in a using directive or as part of a fully qualified class name in order to use the class. The Assemblies part tells you which assemblies you need to add a references to your projects in order to be able to use those classes. In this case MemoryStream is part of the core libraries, so you aren't likely to not have a reference to the required assemblies.
Just use the namespace only
using System.IO;
using System.Media;
Using System is the right thing to do as MemoryStream is class in itself.
Right Click Project -->Add reference --> Assemblies -->System
Using System.IO
Then in code you can make object of MemoryStream.
I thought I'd add one more point, regarding the format of your using directive. You can use a using directive very nearly like that, in order to create an alias for a namespace or class.
For instance, creating an alias for a class like this:
using SP = System.Media.SoundPlayer;
Allows you to do this:
var sp = new SP();
This is such a dumb question, but I can't figure out the lingo to ask Google.
In Java if I wanted to import all subclasses I would use something like
java.util.*
And all of util would be imported.
Firstly, what is the proper lingo for what I'm doing in C# so I can start using Google more effectively. Am I importing namespaces? Libraries? Subclasses? (Can you tell I'm new at this?)
Secondly, since I'm here, how is this accomplished in C#?
PS- I did click on every related question stackOverflow threw at me to see if the answer would pop up. No luck. I'm simply without words to describe what I'm looking for. The example should do just fine but... Anyone who can take a moment to either explain the lingo to me or perhaps simply point me at something that can (in a nutshell, I have a couple books for the long haul) that would be great.
Firstly, let's differentiate between assembly references and namespaces.
Assemblies are what you add references to in your c# project, they are the libraries that contain the actual classes you need, usually found as DLL files. The .net framework contains many such assemblies, and Visual Studio will try to reference the most commonly used ones in your project (e.g. for a WinForms project it will automatically add a reference to System.Drawing.dll).
Namespaces are logical partitions of the classes in an assembly.
Once you reference an assembly in the project, all classes in all namespaces are available for use, if you provide their full name.
This is where the using directive comes in.
It is simply syntactic sugar for not having to write very long names all the time.
For example, assuming your project references the System.Drawing.dll assembly, you would have to qualify a class from this assembly using it's full name, for example
System.Drawing.Imaging.BitmapData
Because this is tiresome and bloats the code, if you start your .cs file with
using System.Drawing.Imaging;
you could then instantiate a class using just the name BitmapData.
This will be true only for the .cs file in which you added the using directive, not for the whole project.
Also, it's important to note that using one namespace does not bring in all nested namespaces, you have to using each one individually.
You must brush up on your your Google-fu
http://www.harding.edu/fmccown/java_csharp_comparison.html#namespaces
It can be called importing / referencing/ using namespace.
Such a language feature is not available in c#.
A little explanation: Namesspaces can be spread across multiple libraries. so when you use a namespace it may refer to it from multiple referenced assemblies.
It's called namespace and it's imported by a keyword using. For example:
using System;
This statement enables you to reference all the classes that exist in that namespace. They, however don't enable you to reference any class in the subnamespace of declared namespace. You have to declare each namespace separately. For example:
using System;
using System.Text;
Of course, you need to have a proper references added to the project where you're specifying the using directive.
Within .Net, you first would need to ensure that there is a referenced assembly containing the namespace you would like to import. Once that reference exists, you can use the 'using' directive to bring that namespace into the class so as to not have to fully qualify all object names. You can find more information on this directive on MSDN.
If I misunderstood, let me know and I'll do my best to get you pointed in the right direction.
The issue is fairly simple, I have some constants in a C++ namespace that I would like to wrap using SWIG 2.0.8. It looks something like this:
namespace Example {
static const float PI = 3.14159f
...
/* Lots of classes are here */
}
Unfortunately SWIG handles this rather awkwardly. In the C# case, it adds the constants to a class with the same name as the namespace so it must be accessed by using Example.Example.PI even when I am explicitly using Example (due to masking by the module name).
In Java, its even worse as it does not treat it as a constant at all and I am forced to call it using Example.getPI() as a method call instead of a constant class variable.
If I move the constants to the global namespace, this seems to work but then the variables must be accessed using ExampleConstants.PI.
Ideally, I would like both languages to be able to access the constants via Example.PI to be consistent with C++. But a compromise that I would be happy with is if I could have a Constants class inside my namespace so that I can use Constants.PI in either language. But of course, C++ does not allow non-integral types to be defined inside a class and this is still not solving the issue in Java.
Is there any elegant way to handle these namespace constants with SWIG?
And if not, is there a way I can manually add a Java or C# class to define them?
I solved similar problem for C++ - C#. I am not sure if this is exactly what you are looking for, but I hope you will find some info useful for you.
I have not touched Java code in my project.
Swig solution.
I created class with public static parameterless functions in C++.
Then I exported them to C# using SWIG.
I specified namespace for C# in command line with -namespace <name> key. More details available at page SWIG and C#
As a result you can impelement solution to access your constant with Constants::PI() and Constants.PI()
Direct solution
If you would like not to use SWIG or other library, you should use PInvoke. There are a lot details and special cases when working with it. Most comprehensive article on subject I have found is Mono Interop with Native Libraries
You should consider JNI for Java.
Note, that C++ functions are exported without namespaces as pure C functions and you should create C# class and create functions with DllImport attribute to wrap functions back to namespaces.
In general if your C++ interface is more or less fixed and/or small I would adhere direct solution, because SWIG layer has many-many specific cases which should be learned along with PInvoke/JNI. But if you C++ interface frequently changed and requires a lot of effort to keep C++, C# and Java consistent, you defenitely need to consider SWIG.
You may find non-trivial example using PInvoke at https://stackoverflow.com/a/11909571/13441
Concerning C++ constants. You can specify C++ constant inside class, refer to C++ static constant string (class member) for details.
I use SWIG 1.3.40.
Hope this is helpful.
I come from Java and see that package in Java is very convenient. When you move a class to another package, it will change automatically the package. (of course, by IDE such as Eclipse or Netbean)
But C# is using namespace and don't have my namespace renamed automatically like it does in Java. For example I have a file which namespace is com.app and I put it in com.app, but at later time, I move this file to com.lib folder and its namespace still be com.app. So, I find this is difficult to manage because I'm moving it manually.
Please give me help in how to fix my problem. (that namespace of file is named by folder it contains, and when I move to other, I will automatically change). Can we do it?
I fix the problem by using an IDE plugin called Resharper. (Among many, many useful features) it highlights when a namespace is wrong (based on the folder hierarchy and root namespace of the assembly) and can fix it for you.
Note that unlike in Java, there are sometimes very valid reasons for a class to be in a namespace other than the one inferred by the directory structure. A good example might be extension method classes, which need to be in scope in the class that is invoking them. Therefore it is common to have:
/myProject
/extensions
/MyExtensionMethodClass.cs
with a namespace like myProject (so that the extension methods can be used anywhere in myProject without a using directive)
Thats actually because C# has the concept of partial classes , that is , you can distribute your C# class along several files instead of just having it coded into a single file , like Java. For that reason , namespaces in .Net are distributed containers instead of centralized containers , defined by your namespace orperator.
I downloaded the OpenSSL .NET wrapper on Visual C# 2010 express edition and I tried to modify the source code by adding methods and classes in the Crypto library. Then I compiled it and generate new ManagedOpenSSL.DLL.
I made a test program and i put this DLL as a reference to check if my modifications were done.
The result is that I found my new methods (I added them to an existing classes) exist, but my new classes does not exist.
Does some one know why ? thanks for any help.
Did you forget to put public in front of your classes?
public class MyNewClass
{
}
Without seeing any of the code you added, I can only guess that either you added internal classes and thus they cannot be seen, you are not looking in the correct namespace for your classes, or in fact you added no classes at all. Again, without your code, these are only guesses.