C# code re-use via namespaces - c#

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.

Related

Can I rebuild .NET class from reference source?

I want to add some methods in System.Net.HttpWebRequest class to suit my needs. I tried reflection but it is quite complicated that I need to alter many of its member class method as well.
I am debugging through .NET reference source and I could view the source code of those class. Is it possible for me to copy each of the related class source code and build my own class?
For some classes yes, but for many no.
.NET classes frequently use internal classes that are not exposed publicly, you would not only need to rebuild the class you are interested in but also rebuild all internal references too.
I would recommend not trying to do this and instead either using Extension Methods or if that does not solve your problem ask a new question describing the exact thing you are trying to accomplish and perhaps we can show you a easier way to do it.
Anything's possible.
You have the source code. You know how to copy and paste. Certainly it's possible you could adapt that code for your own purposes.
The question is; is it legal?
To answer that, you need only examine the license for the reference source. To that end, it's perfectly legal, assuming you comply with the MIT license (which is pretty lenient).
The next question is; should you? Probably not. Most likely, you could just add your desired functionality via a helper class or child class, or add new methods via Extension Methods.

Compiling to DLL

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.

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.

The right way to use Globals Constants

In almost every project, I can't decide on how to deal with certain global constant values. In the older days, when I wrote C++ programs which didn't used dll's, it was easy. Just create and .h file with a number of const that described certain constant values for my project. Then I had every file include it, and ta-da! It worked. Clean, respected the DRY principle and was simple.
Now my projects are C# .Net, which gives me a large range of options to deal with this problem. From what I know:
Create an Assembly whose only purpose is to hold constant values for my project. Every other Assembly should then reference this one. I respect DRY and KISS, since adding references is simple enough. Main problem here is that I'd need to recompile the whole source to update those values.
Use a app.config file and have all other Assemblies retrieve the constant during initialization. So I add the overhead of having to initialize everything just to access a global value. Is more flexible but also more painful.
Use resources. I think it's the same as with app.config.
So, I know there's a better way to do this constants declaration. But I don't know and, so far, have been unable to find how to do it. Can you please help? I have candy!
Thanks all
Er, assuming that your constants aren't enormous, you should just be able to declare them as public const in a class of your choice:
namespace MyProject
{
public class Awesome
{
public const int SomewhatAwesome = 1;
public const int ExtraAwesome = 2;
/* etc */
}
}
You should include your const members in the classes that they relate to, i.e. if SomewhatAwesome and ExtraAwesome are used for and by the Awesome class, then they should be constants declared in that class. Don't create an extra assembly just to hold constant values, and don't create a dedicated static class or namespace for your constants unless there really is nothing else that groups the constants together.
The app.config file is for settings that can be changed by the end user at runtime. Don't put constants that shouldn't change in that file. Resources are for "big" objects, such as text files and images, that would be tedious or impossible to include as literal class members. Don't put simple things like integers and short strings in resources.
You could use the readonly keyword instead of const to avoid having to recompile everything when the values change.
Excerpt from MSDN:
While a const field is a compile-time
constant, the readonly field can be
used for runtime constants
See this link for more details.
For C# projects, if you want constants, arguably the best thing to do is use the Settings file provided in Visual Studio under your project settings. It supports custom types, and AFAIK anything that is marked as serializable.
As many developers have told me, don't reinvent the wheel. There are two setting types, user-settings and application-settings, the main difference being that application-settings are read-only at run-time. That's essentially what you want, it sounds like.
Looks like using a class is Microsoft's recommendation. http://msdn.microsoft.com/en-us/library/bb397677.aspx
If you want the values to be capable of being changed at runtime, use app.config.
If you want them to be fixed at runtime then you're going to have to (and want to, to stop users messing around with them) recompile every time you want to change them, so use whatever's appropriate for your language. In the case of C#, some kind of GlobalValues class/assembly.
Don't use a resource file for global values or settings unless you want to swap sets of values in and out as a group (e.g. when compiling for a different language).
I think the main disconnect here is trying to force a C way of thinking into a C# project. If you have a bunch of constants that you just want to throw in a file together, I would take that as a sign that you need to re-think your design. Spend some time to think about which class the each constant really should belong to and put it there.
That being said, I really don't think you should treat these constants differently from other data, they should live in a dll. This also has the added benefit of being able to version the dll should the 'constants' change.
I have a few projects that I've been working on at work and we decided to create a static class for our global values and functions:
namespace MyNamespace
{
public static class MyGlobalClass
{
//Global stuff here
}
}
That way all global items are always visible and you don't have to instantiate the class to use them.
compile time constants vary with the universe in which you inhabit. So pi and e are compile time constants.
runtime constants could potentially vary with each new version.
settings could potentially vary each new time an application is run (or more often depending on how settings are implemented, i.e. db drive, config file driven, etc).
Try to avoid the God class and static 'helper' classes if you can help it. You should try your best to move the constant data into the appropriate classes.
I'm assuming that since you are using C# you want to develop with proper object oriented designs, principles, and patterns. Remember, objects are about behavior --not necessarily functionality. In my opinion, thinking functionally leads to producing procedural code.
You can use the Singleton pattern when the data is used throughout many objects. Although, it's not necessarily a best practice. Lately, I've started using IoC dependency injection more in these situations with Unity and MEF.

Is it possible to override a method in a class in a dll file?

I've included a dll file into my windows form project.
1. Is it possible to override a particular class entirely?
2. Is it possible to add a new method to a particular class in the dll file?
3. Is it possible to override a method in a class in the dll?
Alternatives I would prefer to avoid:
I know I can use extension methods to create static new methods.
I can also inherit from a particular class and then add new methods to the derived class.
What i'm trying to achieve:
i have to create a project now and add it to a larger project as a dll file.
but we've been told that we'll need to add more functionality to the original project next month. I'm trying to figure out the best way to go about this.
the smaller project is based on mvc design.
You can certainly override a virtual method which you're inheriting from a class in a class library. You do this any time you override object.ToString(), for example!
You can't "override a class entirely" though - I don't know what that would even mean. Likewise you can't add a method to an existing class although you can:
Use extension methods to "pretend" to add another method (but no state, and no properties)
Derive from the class (assuming it's not sealed) and declare your own extra methods
If you could tell us what you're trying to achieve, it would be easier to advise you on how to proceed.
EDIT: When you need to add more functionality to the original project, just add it to the original project. Is there any reason you wouldn't be able to change that project later?
What i'm trying to achieve: i have to
create a project now and add it to a
larger project as a dll file. but
we've been told that we'll need to add
more functionality to the original
project next month. I'm trying to
figure out the best way to go about
this. the smaller project is based on
mvc design.
The current best practice is to use inversion of control (eg. ninject) for these kind of things, if you have a central place for all you dependencies you can wire them up however you like at runtime, intercepting bits and pieces as you wish.

Categories

Resources