The VS 2013 Express forum doesn't seem to exist at Microsoft so I'd like to ask here..
I am using Microsoft VS Express 2013 to create a C# project. I'd like to be able to add a whatever.cs file to the project so that I can put extra functions there instead of in the default Program.cs file. Back in the old days, we could import code files in C by using a #include but C# in the Visual Studio doesn't seem to do this.
I have been able to successfully add a .cs file, create a class within it, and then instantiate the class and call it's methods from within Program.cs but I'd rather not have to instantiate a variable and have to call functions like something.MyFunction() just to execute some code that exists in another file.
Is this even possible? If not, does anybody know why? I always like the #include in C. You could keep things nice and neat.
Files added to a Visual C# project are automatically "included" in every other file within that namespace. You do not need a using statement unless you change the namespace. Because of this, there is no equivalent of the "#include" directive from C/C++.
Now to handle your use case. C# is inherently object-oriented. It is not expected that you create a million functions and call them individually (like you do in C). So, if you want to use multiple files (and you should!) you have a few options:
Create a normal class (as you have already done) and instantiate it to call its methods. This is the preferred method, and you should be able to come up with plenty of classes for your program that make sense.
Create a static class. These don't have to be instantiated (you access them like MyStaticClass.MyFunc(); ). These are often used as "helper" classes. In general, use sparingly as they are hard to unit test/dependency inject.
Mark your class as partial. This allows you to define the same class over multiple .cs files. Again, this should be used sparingly (see Jon Skeet's answer: https://stackoverflow.com/a/2895068/1783619)
Related
Now I programmatically generate sources and create some classes before compilation and obviously add it to project in solution. Maybe it is possible to "silently" add classes before compilation without creating .cs files in disk and not showing these classes in Solution Explorer (maybe using Roslyn).
EDIT: I must not use any runtime code generation.
You can put the classes in a separate DLL (class library). When you create that DLL using another solution you will not see the classes in your solution explorer of the project where you include them.
Don't forget to add a reference to the DLL (class library) in your main project.
You could probably do something with MSBuild, creating a custom project target which does the work, but I've never done this.
What I have done recently which is now achievable on the DNX-based ASP.NET 5 platform, is a concept known as meta-programming. I've written a blog article about this concept specifically with examples of generating code at compile time. In my particular example, I've got a class that won't compile, but then with an introduction of an ICompileModule, I can fill in the missing method return statement at compile time.
This is possible because in DNX-based applications, the RoslynCompiler class actually supports loading instances of ICompileModule at compile time, and then running these instances before your main project compilation. This enables you to add/remove/replace syntax trees in the compilation before the compiler finishes its work.
If you're looking to develop on ASP.NET 5, this could enable you to do what you need, but I don't know how you would go about doing this otherwise.
Seems quite aspecty to me.
I asked a question which I also answered myself about engineering a compile-time solution that performs code generation for another scenario:
Getting interface implementations in referenced assemblies with Roslyn
And lastly, other examples where this might be useful, and something I've been toying around with, is the ability to generate EF-style migration classes from .sql files embedded in my assemblies. All these scenarios are now easier for me to implement on ASP.NET 5 + Roslyn.
Without knowing your use-case properly, here's an idea...
Create a VSIX that listens to an 'on build' event
Upon initialisation of the build, the VSIX creates your new classes*
The same VSIX will also listen for a 'build complete' event
Upon completion of the build the VSIX would tear down the new classes
*Your question states that the classes should not be created on disc, so the VSIX could
create the classes as a memory stream (?)
add the new class as code within existing files on disc
create the new class as a new file on disc (or cloud ?) in C:\Temp or elsewhere
the new class could be part of a partial class (either a real partial class in your application or an empty new dummy partial class)
In any case the project file would need to be auto-edited (by the vsix) to reference the new file(s). Presumably you want the project file reverted aferwards ?
And if, unlike me, you want to get down and dirty, you could always interfere with the IL, but you're on your own there !
As TarkaDaal says, without knowing why you need this it's not easy to provide a more definative answer.
I have found a math parser Here. I have never added something like this to a program and was wondering what I need to do to add thing like this to a program. For example I want to know where to put the file and how to call it in the headers so that I can use the classes inside the file. I looking for general instructions that can be applied to other things as well.
Sounds like you have come from a bit of a C background. C# is a little different in the way that we pull in external code, and its actually quite a bit easier than C.
To reference some code using Visual Studio, you will need to add a reference to that dll. once you have the dll included (via a reference) in your project you can use it in your code by adding a using statement and then instantiating objects from that library
MSDN docs around this are here: http://msdn.microsoft.com/en-us/library/wkze6zky.aspx
EDIT:
if you are outside of VS as you have specified there's a few things you will need to do:
Let your compiler know where the assembly is so that it can correctly link
Add the assembly to your running directory (it should sit alongside your executable)
OR add your library to the GAC
OR manually load it with an Assembly.Load call
i am learning extension method, a very handy feature, which can save number of hours of coding, provides reusability. what i'm doing now a days, daily i'm creating 10 extension methods which useful in day to day scenario. but i'm not getting how to use these extension methods, everytime we need to add dll and reference it. or is there any smart way where we can use .
suppose
public static bool isValidMail(this string str)
{
Regex reg = new Regex(#"^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$");
return reg.IsMatch(str);
}
if i created 100 extension methods like this , then for every project should i need to reference this static class dll. as i work with multplie projects. is there any way that we can put these extension methods in centralized location or some assembly cache, where we can easily add using statement and get access to all static methods.
can we do like this ?
whenever we do create new project, can VS automatically add the extensionmethods which we created, so that in evey project we can access it. rather than adding dll everytime
i want to know how you people do.
i hope no one down votes it, just curious abt implementation of extension methods
It sounds like you should have a single project containing related extension methods - and then yes, you'll need to add a reference to that project from every project which needs it. That's a one-time cost. You could put it in the GAC, but personally I wouldn't - just treat it as another class library you need to depend on, like any other.
You could change the VS 2010 Project Templates to include a "Framework" DLL automatically.
visual studio templates
I simply keep a common repository of various common dll's and reference the ones I need, this is in SVN as well, I then have specific Snippets for each Framework I have created to make it easy to insert commonly used code.
With python, I can use if __name__ == "__main__": for using the module both as a library and a program.
Can I mimic this feature in C#?
I see a class in C# can have a 'static void Main()', but I'm not sure if every class can have a Main() without a problem.
ADDED
/m:CLASS_NAME is a way to specify the class to run the Main().
You can put a Main method in as many classes as you like, although only one can be an entry point for an application. (For talks, I often have a main method in every class, and use a helper library to present all of those pseudo-entry-points when I run the project.)
Likewise you can definitely add a reference to a .exe assembly and treat it like a library. For example, you could make a unit testing assembly work like a class library in most cases, but also write a main method so that you could just run it to execute the tests without a GUI or whatever.
You can compile a C# project as a program (executable) with a Main() method, and you'd still be able to use it as a library. No special syntax required.
You could add a Main() method to every class, but I doubt it's useful.
.NET applications usually have different structures than Python ones; trying to fit the same programming model is unlikely to get you good results.
C# project files specify a startup object when multiple entry points are available.
See this article for more info.
I like to create a file full of custom functions which I have made, which I may use in another project or something. Now I don't fully understand how to go about this, normally in a language like php, you'd just create the php file and then go include("cust_lib.php") or whatever the file is called.
Now I think that the process involves the library having its own namespace, then either go using custom_lib; or custom_lib:: within the script (I don't want to get into a discussion over which is the best way to go here).
Is this right? Or should I create the library and convert it to a .dll, if so how do I go about this, what sort of syntax does a dll have inside it etc.
However if its just file within one project then I don't need to go down that route do I? I can just create the namespace and use that?
This is what I'm working for at the moment, and thought it would be something like this
namespace Custom_Lib{
~~functions to go here~~
}
However the functions have to exist within a class don't they? So that becomes something like
namespace Custom_Lib{
class custom_lib{
public string function1(string input){
return input;
}
}
}
So some help, pointers, examples would be appreciated so I can wrap my head around this
Thanks,
Psy.
(Yes I call them functions, that just comes from a long php/js etc background)
The normal approach would be to create a Class Library project, put your classes and methods in that project, making sure that those you want to expose are public. Then you add a reference to the resulting dll file in the client projects and you will have the functionality from the class library available to you.
Even if you decide to put it all into one single file, I would still recommend you to make it a class library since I imagine that will make it easier to maintain. For instance, consider the following scenarios:
You decide to put it in a file and include a copy of that file in all projects where you want to use it. Later you find a bug in the code. Now you will have a number of copies of the file in which to correct the bug.
You decide to put it in a file and include that same file in all projects. Now, if you want to change some behaviour in it, you will alter the behavior for all projects using it.
In those two cases, keeping it as a separate project will facilitate things for you:
You will have only one copy of the code to maintain
You can decide whether or not to update the dll used by a certain project when you make updates to the class library.
Regarding the syntax issues: yes all methods must exist within a class. However, if the class is merely a container of the methods, you can make it (and the methods static):
public static class CustomLib
{
public static string GetSomethingInteresting(int input)
{
// your code here...
}
}
That way you will not need to create an instance of CustomLib, but can just call the method:
string meaningOfLife = CustomLib.GetSomethingInteresting(42);
In addition to Fredrik Mörk's well-written and spot-on response, I'd add this:
Avoid creating a single class that is a kitchen-sink collection of functions/methods.
Instead, group related methods into smaller classes so that it's easier for you and consumers of your library to find the functionality they want. Also, if your library makes use of class-level variables, you can limit their scope.
Further, if you decide later on to add threading capabilities to your library, or if your library is used in a multi-threaded application, static methods will likely become a nightmare for you. This is a serious concern, and shouldn't be overlooked.
There no question here. You answered it yourself. Yes, you have to construct a class to include all helper methods. And yes, you can either compile it to a dll if you want to reuse in multiple projects it or just add the source file to the project.
Usually I declare the helper class and all functions as static to avoid initiating the class each time I use it.