C# "linking" classes - c#

I'm starting a simple C# console solution via Mono on Mac OS X.
I have a Main.cs file for starters, but I want to create a separate class and be able to access object of that class from my Main.cs file.
How can I access that class from the Main.cs file?
Say my class name was Math.
In my Main.cs file, can I create a new object like so:
Math calculator = new Math()
Without referencing the class in the Main.cs file in any way?
Or, do I have to use some sort of import statement/directive?

You need a using statement if your Main and Math are in different name spaces, otherwise it just works. Below is an example. The using System brings in the library that contains the Console class, but no using is required to use the Math class.
Program.cs:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Math caclulator = new Math();
Console.WriteLine(caclulator.Add(1, 2));
}
}
}
Math.cs:
namespace ConsoleApplication1
{
class Math
{
public int Add(int x, int y)
{
return x + y;
}
}
}

There are two scenarios here. Either this class is in a separate dll (class library project), or under the same project. To reference within the same project not additional work is needed, other than referencing it with the correct namespace (as mentioned in other posts).
In the case of a separate dll, you need to add a refence to the project in the project definition. Most default projects come with a reference to System.dll and other related libraries. It is recommended to name your dll's based on what namespaces are defined within it. If you have classes like Foo.Mathematics.IntMath, Foo.Mathematics.DblMath then I suggest you name it Foo.Mathematics.dll.
When I was where you are, I picked up .NET Framework Essentials from O'Reilly and it had answers to all my questions at the time.

Related

Can't utilize an existing Class in a new C# project?

I'm a student learning mainly C++, but this term we have to code our math assignments using C#.
Our professor supplied a basic skeleton program but I'm not very good at C#. He gave us two class files (.cs) but when I add them to my project, I'm unable to utilize them at all. I can't create a class object from either class.
The classes are just Line3d and Point3d. They have the variables needed to compute points and collision.
Thanks for any advice.
Compile your project.
Use Ctrl + . or bulb icon (type your class name you want to use and locate your cursor position over that class name) to resolve namespace for these classes or write using directive manually.
C# classes are normally encapsulated in namespaces. In Visual Studio, adding a new class will generate a file containing a namespace similar to PROJECT_NAME.SUBFOLDER.SUBSUBFOLDER For example:
// MyClass.cs
using System;
namespace MyProject
{
public class MyClass
{
}
}
And then you can reference that from another class in the same namespace, but you can't reference it from a class in another namespace (unless it's a namespace that starts with MyProject.).
// Line3d.cs
using System;
namespace TemplateProject
{
public class Line3d
{
}
}
// MyClass.cs
using System;
namespace MyProject
{
public class MyClass
{
public Line3d LineInstance {get;set;}
}
}
In this example, it won't work because the compiler doesn't know which namespace Line3d exists in (and, indeed, two class with the exact same name could exist in two different namespaces). You need to instruct the compiler to include classes from the TemplateProject namespace (note this doesn't include classes in the TemplateProject.ChildNamespace namespace):
// MyClass.cs
using System;
using TemplateProject;
namespace MyProject
{
public class MyClass
{
public Line3d LineInstance {get;set;}
}
}
Now you should be able to find the Line3d class and use it.
Besides manually referencing the namespace, you can also right-click an unknown class reference, select "Quick actions and Refactorings...", and then you will see something like "using TemplateProject;". Click on this and it will automatically add the using for you.
You can also use the Ctrl+. keyboard shortcut, which does the same as right-click/Quick actions, if you don't want to use the mouse.
select your project and press [ Shift + Alt + A ] to add existing files.
you can see dialog form that allows to open cs file on project.
After that, you can use professor's class files.

Having a Main() routine in a separate file from a Class in C#

I recently branched out into C# written with Visual Studio Express from C++ written with gVIM. I've been told I'll have to unlearn a lot of stuff to really use C# effectively, but here's my question:
In C++ when writing a class or data type, I would have separate files for the class definition and the driver program. I would then #include the class in the driver program in order to use it. It isn't terribly clear how to do this in Visual Studio Express 2013 and all the tutorials I've looked up have the class definition and the Main() routine in the same file.
I currently have only two files in my solution folder: the driver program p1.cs and the type definition/implementation targetInt.cs. What is the best way to allow p1.cs to work with my targetInt.cs type? Will it simply have access by virtue of being part of the same solution? If so, how to I get around not having a Main() routine in my type definition?
Here is a screenshot of the solution and the error I'm getting when I try to build the solution. I don't get an error for trying to declare a targetInt object in p1.cs which points to the namespace already being shared.
http://i793.photobucket.com/albums/yy218/tombombodil/solution_zps6a743e2d.png
Let me know if I need to clarify anything.
It's really not terribly complicated, but it is different from C++. So if you have one file that looks something like this:
namespace MyNamespace
{
public class MyClass
{
//...stuff
}
}
And then you want another file with your Main (which you will for anything more than a trivially simple project), it would look something like this:
using MyNamespace; // unless you use the same namespace for both
namespace SomeOtherNamespace
{
class Program
{
static void Main(string[] args)
{
var c = new MyClass();
// alternatively, without the using statement, you can just fully qualify
// your class name like so:
// var c = new MyNamespace.MyClass();
}
}
}
But do note that the files need to be in the same project. If they are in different projects you can still do it, but you have to add a reference to the project with MyClass to the project with Program. What you can't do is just have an orphaned C# file floating around in your solution and expect it to work.
The problem as you've written boils down to the simple lack of shared namespaces - because targetInit exists in a separate namespace, Program needs a using targetInit.cs to access the targetInit type. They can, however, access each other by virtue of being in the same project - a Solution can contain multiple Projects, and if they don't reference each other, they can't access each other's types.
Usually, the naemspace of any given class is actually the folder path to it, and the class name is the same as the file name (which Visual Studio does for you when you make new class files).
As for the Main() definition, you only want one of these since you only have a single entry point for the system to jump to when your program begins - having multiple Main() functions doesn't make much sense when the OS needs a clear place to begin execution.
The Main() method and class definitions sitting in the same file is a convenience so all the code can be read together - to get an idea for how actual projects are set up, trying going to GitHub and forking a couple of open-source projects.
there are two approaches to use another class in C# directly:
1-putting that class in the same namespace of my class(even if they were in separate files), this code clarify this:
//file TargetInt.cs
namespace MyNameSpace
{
class TargetInt
{
}
}
//file p1.cs
namespace MyNameSpace
{
class p1
{
static void Main(string[] args)
{
}
}
}
notice that both classes are in MyNameSpace namespace.
2-if the other class is contained within another namespace, you can simply use it by declaring this statement in the upper beginning of the file:
//file TargetInt.cs
namespace OtherNameSpace
{
class TargetInt
{
}
}
//file p1.cs
using OtherNameSpace;
namespace MyNameSpace
{
class p1
{
static void Main(string[] args)
{
}
}
}
with using OtherNameSpace; you can use TargetInt class directly.

How to add an extension method to .Net assembly?

I am new to software development and may be I am asking a very silly question but, I am curious to learn more on this thing.
Is it possible to add an extension method to .Net assembly? I want my extension method to work on every project I am working on. Apart from referencing to my own assembly, is there any other way?
If it is not possible, please explain taking some time.
Thanks in advance :)
There's no way of adding methods to an existing assembly.
There's no other way than creating it in your own assembly and referencing that.
Create a new project as a dll (class library)
Add your extention classes/methods to this dll
Reference this dll in your future projects
In response to your comment, you cannot modify the .net framework, only build your own dll's to include methods you wish to share between projects.
The reason you cannot modify the framework is because the code has been compiled already.
You can create extensible method in class but not possible in your reference dll
please check here extensible class method
Is it possible to add an extension method to .Net assembly?
this itself says that you have to create your own methods to extend .Net assembly which are already deployed. The only way to use is define your own methods and include the namespace in the code where you will use these extenssion methods.
sample. of Extenssion methods.
using system;
namespace myNamespace
{
public static class MyExtMethods
{
public static string Foo(this string bar)
{
return bar+ "Some values added. ";
}
}
}
Uses of Extenssion Method.
using system;
using myNamespace;
namespace myNamespace2
{
public class Program
{
public static void Main(string[] args)
{
string str ="Some Value";
Console.WriteLine(str.Foo());
}
}
}

Can I "add" static methods to existing class in the .NET API?

I want to build a Windows Store class library using source code from a regular .NET Framework class library. Ideally, I do not want to modify the original source code files.
In some of the source code files from the .NET Framework library, static members are used from a class that is defined in both the regular .NET Framework API and the .NET for Windows Store apps API, but where only a subset of the .NET Framework members are available for Windows Store.
One specific example is System.IO.Path, where the GetFullPath method is not available for Windows Store apps.
It is fairly straightforward to incorporate a replacement for this method in my Windows Store class library and have the original source code invoke this method instead. My question is, is there any way I can do this without modifying the original source code file?
So far, I have not been able to figure out a satisfactory solution to this problem, but I have solved it for my Windows Store class library by implementing e.g. the Path.GetFullPath(string) method in another namespace:
namespace WindowsStoreLib.System.IO {
public static class Path {
public static string GetFullPath(string path) { ... }
}
}
and then adding a preprocessor directive in the original files:
#if NETFX_CORE
using Path = WindowsStoreLib.System.IO.Path;
#endif
Is there an alternative solution to this issue that does not require modification of the original source code files?
No, you cannot, simply.
When I'm doing cross-platform stuff I tend to write a utility class that has different implementations (via #if) for different platforms - then my core code just calls the utility class.
I've been doing something like this lately with Entity Framework classes since I needed to add a specific output of 2 fields as 1 and it wiped it out from the designer.cs on every update. However they were not static classes or static methods, but should work with same.
Create a new class file with the name of the class you want to extend and use the partial qualifier.
namespace WindowsStoreLib.System.IO {
public partial static class Path {
public static string GetFullPath(string path) { ... }
}
}
As Marc said, the preprocessor directive seems to be the only solution.
But when I read "static class" and "existing class", the first thing coming to my mind is "extension method". What would happen if you created an extension method for Path in the same namespace where your code is?
namespace MyNamespace.WhereMyCodeIs
{
using System.IO;
public static class ExtensionMethods
{
public static string GetFullPath(this Path pathObject, string path)
{
// Implementation
}
}
}
I am really not sure if this would work out but maybe there is a work around we could find around this.

How do I work with multiple files and C# libraries in F#?

I have a C# library with the following Namespace/Class:
namespace Helper
{
public static class Util
{
/*static methods*/
}
}
I have referenced said library in a F# project and when I try to call one of the methods I get:
error FS0039: The namespace or module 'Helper' is not defined.
This is an example of the method call not working:
#light
let a = Seq.skip 1000 (Helper.Util.GetPrimes 200000);;
Am I missing something obvious? Using open Helper doesn't work either, and the weird thing is that IntelliSense does work, it lists every method in the Util class.
Also, what is the standard practice for calling functions in some of my files from other files in the same project? I don't wanna create full objects just to access a few functions.
Regarding multiple files, see the first portion of "Using multiple F# source files, and a useful debugging technique", as well as the final portion of "Sneak peeks into the F# project system, part three". The former discusses how top-level code in a file implicitly goes in a module of the same name as the filename, whereas the latter discusses how to order files in the project (since you can only see stuff declared above/before you).
What does your GetPrimes method look like? It work for me...
I have a solution with a C# library including this code:
namespace Scratch
{
public static class Util
{
public static IEnumerable<int> GetNumbers(int upto)
{
int i = 0;
while (i++<upto) yield return i;
}
}
}
And calling it from a F# project that references the C# project like this:
#light
let p = Seq.skip 1000 ( Scratch.Util.GetNumbers 2000000);;

Categories

Resources