Compiling to DLL - c#

I have a couple of functions which I would like to add to DLL. I found this programming guide How to: Create and Use C# DLLs (C# Programming Guide). It's very short and looks like a really simple thing to do but I've noticed that each single function added to dll is enlosed in a separate file, separate class and functions are static. Is it always the case? What if I have a couple of overloaded functions, such as:
public void WaitForTheKey(object o = null) {}
public void WaitForTheKey(string message, bool addlines = true, int[] quantity = null) {}
private void _WaitForTheKey(string, bool, int[]) {}
Shall I put them in separate files like in the tutorial? Thanks.
EDIT.
If projects for DLL do not require separate classes and files, what would be the reason an author of the tutorial followed this theme?
Thanks

First of all you should keep you logic split by functionality. So all these methods you should keep in one class (in most cases it means one file).
It is very simple to create dll. If you use Visual Studio you should pick Class Library project type and then simply build it. As a result you will get dll file. Or use compiler directly from command prompt like it was shown in tutorial.

You are overthinking it; the tutorial is just an arbitrary example.
Simply structure the code in a way that makes sense, with as many or few classes as you like. Everything that is public in your assembly (classes, methods, properties, fields, events etc.) can be accessed by the consumer of the DLL.

Related

How to get various types used in a C# project with Roslyn

I am analyzing about converting an existing C# library to java. To start with I need to know what are the types / built-in keywords used in the existing C# library. I mean, for example
public class CSharpClass
{
int i;
float j;
Console.Writeline(String.Concat("A","B"));
}
In this class the types/Keywords used are,
public
int
float
Console
String
My Questions are,
Is there any way to do this. I hope I can do this with Roslyn. But we can get “LocalDeclarationStatementSyntax” for variables. But how to parse “Console” and “Concat”. Is that “Sytax walker” that parses all the tokens in a class is the only option?
Also how to get all the classes from a project file with Roslyn?
You need to semantics as well -- syntax is just the text you see and that's exactly what you get, nothing more, nothing less. Get a Compilation for your project, then you can call GetSemanticModel where you give it a tree, and then from there you can call GetTypeInfo or GetSymbolInfo (as appropriate, search online for the difference between these two) to get type information.
As far as getting the Compilation, if you're writing a command line tool you probably want to use MSBuildWorkspace to load your project. If you're analyzing the projects open in Visual Studio, use VisualStudioWorkspace, etc.

how to use extension methods across many projects .

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.

if __name__ == "__main__": equivalent in C#

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.

Include code file into C#? Create library for others?

I would like to know how can I embedd a code source file (if possible), something like that:
class X
{
include "ClassXsource"
}
My second question - Can I build DLL or something like that for my colleagues to use? I need them to be able to call methods from my "part" but do not modify or view their content. Basically just use namespace "MyNamespace" and call its methods, but I have never done anything like that.
Thanks
The C# compiler does not support include files. You can of course use a pre-compiler, that would read your source code files, and insert the included files into them, before passing the new files to the compiler.
As for producing a class library, sure. You can do it in two ways:
You can make the project source code available, so that they would add the project with all its files into their own project, and thus compile your class library as part of their solution.
You can compile it yourself, which produces an assembly file on disk (YourClassLibrary.dll), and then give that file to your co-workers. They would then add a reference to the file and can start using it.
You can't, except by using some external preprocessor. You could use T4, which is already used by Microsoft as a text templating tool, e.g. for code generation with the Entity Framework; see this MSDN documentation page.
With T4, you would include another source file like this:
<## include file="c:\test.txt" #>
Now to the more fundamental point: Including source files is not how you usually create libraries, especially not in .NET. What you would do is define one or more types containing the functionality—there are no global functions in C#, the closest you can get are static methods. You would then compile this and give the resulting assembly (.dll file) to your colleagues. (Or you create a NuGet package and publish it to a source that your colleagues can access.) They will be able to load it as a reference into their .NET project and use your class.
public static class MyFunctions
{
public static void MyMethod1(...) { ... }
public static int MyMethod2(...) { ... }
...
}
(Of course such code is more procedural than good object-oriented design, but this may or may not be an issue for you.)
No, not in that way. But you can create a class library and put all classes they need to use there. They simply add a reference to that dll from their project and import the namespace, voila, they can use the classes.

C# code re-use via namespaces

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.

Categories

Resources