Where should I put miscellaneous functions in a .NET project? - c#

I found myself having to remove the first line of a string quite often while working on a text parser in C#. I put together a simple function to do that for me, but coming from a PHP background, I have no idea where to put it since I can't define a function outside a class. What's a customary way of doing that in .NET? Do I create a static class to store my function?

I generally make a Helper or Utility static class and then put corresponding helper functions in there.
Additionally, I try to keep the Helper and Utility classes grouped logically - putting the text parsing functions alongside the object conversion functions is nonsensical. The confusion is cleared up with a TextUtils class and a ConversionUtils class.

Yes, static helper classes are usually the way to do this.
Also, in C# 3 you can declare the method like this:
public static string RemoveFirstLine(this string s) {
...
}
to make it an extension method. Then you can call it on any string as if the method was declared on the string type itself.

Be careful!
Generic utility functions which are cross cutting should live in a higher utility namespace. String parsing, File manipulation, etc.
Extension objects should live in their own namespace.
Utility functions that apply to a specify set of business objects or methods should live within the namespace of those objects. Often with a Helper suffix, ie BusinessObjectHelper. Naming is important here. Are you creating a container for miscellaneous methods, or would it make more sense to group them into specialized objects, ie a parser?

I don't think there's a standard for this. I tend to make a static class called BlahUtil. For your example, I'd make it a static method on StringUtil. This helps me group related methods into sensible units, making it easier to discover them and share them across teams.
You can also then choose which of these methods are exposed as extension methods (since c# 3.0):
public static class StringUtil
{
public static string RemoveFirstLine(this string multiLineString)
{
// ...
}
}

If you are using C# 3.0, you might want to consider using an extension method!
public static class StringExtensions
{
public static string RemoveFirstLine(this string myString)
{
return myString.Remove("line..!");
}
}
Then in code you can do this:
string myString = "Hello World etc";
string removedLineString = myString.RemoveFirstLine();

Usually I create a Utilities class and define static helper methods.

I've done the static "helper" classes but after some analysis; this type of helper function always ends up as a distinct class implementation. In your case you'd have a "basic text parser" class and a derived class that overrides the "parse" method.

I'd create a static worker class for such functions. Maybe not the nicest way, but the one which keeps things simple... ;)
K

Use an extension method for a string. That's what they are for.

You can use a class with static methods. Something like ParserUtils.RemoveFirstLine(). On .NET 3.5 and above you can sometimes use extension methods when your utility functions are related to a class you cannot modify, like the String class. Intellisense will show the extension method on any string object in the project.

Extensions are the way to go in those case. It literally add your function to the occurence. Only thing is that it's not possible to do static method in 2008.

Related

C# in Unity 3D/2D: Am I required to use Classes for every script?

A little background: I'm new to C# and Unity, but catching on very quickly. I'm also hoping this thread will not spark a debate about the merits of classes and abstract coding, as that debate is unrelated and well-worn (and unnecessarily heated); so please keep that in mind.
I'm simply wondering if every C# script in Unity is required to have a main class in any way or for any reason.
Or instead, can methods, and variables can be written outside of a class in a blank file (with namespaces) to be used in a video game?
I'm asking because, when I create a new C# script, it seems to force a class into my file and I'm afraid of breaking things.
I hope to keep code abstraction to a minimum, and the current project
I'm working on has several situations where a class is not needed, or
only one instance of the class will be used. I'd like to simply avoid
using classes in those cases.
In terms of declaring/defining variables and methods outside of any class, you can't really do that in C#. It just isn't how the language was designed (the answers to the question I linked to expand on that idea, so I won't duplicate them here).
You're not without options, though; if you have a number of variables or methods that need to be accessible from different places and don't need an object reference, you can make them static, so you won't need to instantiate the class to make use of them:
public class UtilityClass
{
public static float GravityConstant = 3.51f;
public static string GameName = "MyFirstGame";
public static float CalculateProduct(float a, float b)
{
return a * b;
}
}
Then, you can reference the class's methods/members by accessing it through its name:
float product = UtilityClass.CalculateProduct(6, 1.5f);
An example of where you might use this pattern is when defining mathematical formulae which aren't included in Unity's Mathf methods, and using them in multiple classes.
Additional note: Creating a new C# script through Unity's editor UI will default to declaring a class of the same name that inherits from Monobehaviour. You can alter it to remove the inheritance from Monobehaviour if you don't need any of the methods/attributes of the class, which avoids unnecessary overhead. One example for this would be with a static class that you never need to instantiate.
Yes, you are.
In C#, things like global variables and functions just do not exist. Everything must be contained in a class.
"But what should I do in order to declare some stuff that can be accessed everywhere, without creating an object?" you asked. There is something called the static modifier. You can access the methods or variables or fields or properties marked with this modifier without creating an object of that class.
You just add the word static in a method and it becomes a static method! How simple!
Let's see an example.
I have this non-static method:
public class MyClass {
public void DoStuff () {
}
}
I can call it like this:
var obj = new MyClass();
obj.DoStuff();
But if I modify it with static,
public class MyClass {
public static void DoStuff () {
}
}
I can call it like this:
MyClass.DoStuff();
How convenient!
Note:
Please do not misuse the static modifier! Only use it when it makes sense! When? When the method is a utility method or when the method does not belong to individual objects but the class itself.
First of All you need to check where Methods define as offical
docs stated
"Methods are declared in a class or struct by specifying the access
level such as public or private...."
So, Method should be declare in a Class or struct and A given class
should be, ideally, responsible for just one task.(see also)
Your this question "Or instead, can methods, and variables can be
written outside of a class in a blank file (with namespaces) to be
used in a video game?" answer is hidden in the below question.
Can there be stand alone functions in C# without a Class?
No. Make them static and put them in a static utility class if they indeed don't fit within any of your existing classes.
You have to make a class in order to use methods or its variable
either instance class or static class.
Am I required to use Classes for every script? Every script means you required a class. Unity Support Component Based
Architectural Design and if you require any script related
work then you definitely require a script component which means a
class require.
Finally for singleton, thanks to Unity3dWiki great detail
available. I think you will be feel comfortable to code and writing
class if you keep in mind component based architecture of Unity3d.
Singleton vs Static: I will also recommend to check this: Why do you use a Singleton class
if a Static class serves the purpose
Hope it will help.
[Note: If this helpful Any one can update this answer for future reference and use].

Using "helper classes" in winforms, C#

I tried to ask a question yesterday but it was seemingly too vague. Here's another try.
In the past, I have used some winforms/VB.Net classes with functionality for, say, working on text strings, for file operations, or for database handling, like clsStrings, clsIO and clsDB. The idea was that these classes did everything related to the subject, so that clsStrings would have a method called "filterString", removeCertainChars" etc.
In the old winforms application, I simply wrote Imports clsStrings when I needed to access a method. Throughout the .vb file, I could then write something like
str = filterString(TextBox1.Text)
I now try to get the same functionality in a new winforms app in C#. The only thing I get to work is creating a variable for the class:
clsStrings clsstrings = New clsStrings();
...and then later in the code:
str = clsstrings.filterString(TextBox1.Text);
So I guess what I would want is the ability to use a using statement for these "helper classes" (is there a better word for them?) so that I wouldn't have to write the variable name all the time. (Just like when Intellisense discovers that a namespace is missing and asks if I want to have a using statement for, say, System.Data so I can write "DataTable" instead of having to write "Data.Datatable" all the time.)
I suspect I would need to put these class files in a separate folder or so, but that would be totally fine. I just want some structure to my app.
I hope this is clearer.
Thanks for any input!
Well, the difference is that now you are working with OOP principles.
What you could do to be closer to what you were used to is to build static classes for the helper class, maybe even turn them into extension methods.
Example:
public static class ClsStrings
{
public static string FilterString(this string stringToFilter) { return something; }
}
Then you could call it like this:
string filteredString = TextBox1.Text.filterString();
or
string filteredString = ClsStrings.filterString(TextBox1.Text);
Extension methods is the way to go here. Using these you can basically exten String class with your own methods and do something like Sting.filterString();
http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx

Why do static methods need to be wrapped into a class?

Sorry for the unlearned nature of this question. If there's a simple answer, just a link to an explanation will make me more than happy.
After 6 months programming I find static classes to be somewhat useful for storing routines that apply to many different classes. Here's a simplified example of how I use static classes, it's a class for parsing text into various things
public static class TextProcessor
{
public static string[] GetWords(string sentence)
{
return sentence.Split(' ');
}
public static int CountLetters(string sentence)
{
return sentence.Length;
}
public static int CountWords(string sentence)
{
return GetWords(sentence).Length;
}
}
And I use this in obvious ways like
class Program
{
static void Main(string[] args)
{
string mysentence = "hello there stackoverflow.";
Console.WriteLine("mysentence has {0} words in it, fascinating huh??", TextProcessor.CountWords(mysentence));
Console.ReadLine();
}
}
My question is: Why is it necessary to wrap these static methods in a static class?
It seems to serve no purpose. Is there a way I can have these methods on their own not wrapped in a class? I know encapsulation is beneficial but I don't see the use for static methods wrapped in static class. Is there something I am missing stylistically or otherwise? Am I completely barking up a silly tree? Am I thinking too much?
In C#, any method has to be declared inside a class. That's just how the language is specified.
A static class is actually more akin to a module than a class, so I too think you should be able to either:
define a function outside a class or;
import a module the same way you import a namespace (with using)
VB.NET, F# and Nemerle actually allow you to declare modules and import them; what allows you to use their methods unqualified.
This is valid Nemerle:
using System.Console; // import static methods in the Console class
class Hello {
static Main() : void {
WriteLine("Hello, world!"); // unqualified access!
}
}
Also, take a look at extension methods, they might allow you to "solve" this in a different way. The methods in your TextProcessor are begging to be string extension methods.
This post by eric lippert gives a pretty detailed explanation. I'm not sure if this guy "eric" knows what he's talking about or not though ;-)
It would be somewhat awkward to have methods just dangling around in a random namespace.
I suspect the answer is to provide "scope". Just because a method is static, doesn't mean it doesn't have a scope. It can still access other static private methods or member variables - and the class provides a "home" for these things to live in.
Static classes can also have static constructors that get called the first time a static method is used, so this provides the ability to set stuff up as needed.
It's more of an organizational design than anything to due with technical limitations.
A static method is a method called in a single instance of a class that is created at run-time.

should i use extension method or member method in this case?

for example,
class Aclass
{
void method1()
{
int[] a = new int[5]{1,2,3,4,5};
var b = a.Accumulated().ToArray(); // so that b = {1,3,6,10,15}
}
}
Currently Accumulated() is an extension method. However an equivalent approach I reckon is to define a private member method in Aclass so that MakeAccumulated(a).ToArray() gives {1,3,6,10,15}.
What is a good practice?
Aclass is a place for methods which make logical sense for Aclass objects; best practice is to not use it as a general store for helper functions. A good rule of thumb is that if a method never references member variables then it might be out of place in the class.
A function on int arrays probably has no place in Aclass. I'd put it in an extension method.
it's not a question of good practice but of preference. both are valid options. if you need the method only in instances of Aclass then I'd limit it to a class method, that's also more obvious to others inspecting the class.
I would choose the member function approach, cause extensions methods, I personally, choose for something I'm not able to extend, or have a problem to extend to (complexity, not mine code, serialization issues, whatever...). In your case, you have a class written by you, so just extend it, by following clear OOP design.
For extension methods, you need to define another class, for someone who is not very familiar with your code, or for you after 2 years, will be not very clear why it's done in that way.
Regards.
If .Accumulated() is only going to be called from instances of Aclass, make it a member of the class. It wouldn't be practical to have an application-wide extension method for int[] (or Ienumerable as someone else pointed out) if it's only used within an instance of one class. Keep in mind that extension methods are just for added extensibility.
public static string Hello(this string Value) { return Value + "Hello"; }
string s = "Hello".Hello();
...is the same as:
public static string Hello(string Value) { return Value + "Hello"; }
string s = Utilities.Hello("Hello");
Would you put .Hello() in a utility class if you're only going to use it within the instance of another class? If you use .Accumulated() elsewhere in the application, though, an extension method would work.

Standalone functions in ASP.net

Never seen this done in asp.net, but never the less, can I define functions without being part of the class?
What I would like to have is a utility library. Currently I have Utils class and every time I need to use it for things like populating drop down lists i have to create and init the Utils() object...any way around that hassle aside from declaring the class static which I would rather not do as I access session in it?
I am using c#, not VB.
Thanks
There's no way to have methods outside of classes.
The typical solution in your case is to create a Utility class full of static methods...that way you don't have to worry about creating an instance of the class to utilize its methods.
And like Joel mentioned...you can still access the session from a static method.
You can always use Extension Methods.
http://msdn.microsoft.com/en-us/library/bb383977.aspx
You can then add the methods on to the existing objects.
You could also create a base class which all your pages inherit from and have that contain the methods you need. It's still part of a class, but you don't need to instantiate a new one, or use static methods.
You can still access Session variables in a static class. One way might be like this:
public static class Utils
{
private static HttpSessionState Session
{
get { return HttpContext.Current.Session; }
}
public static string DoThing(string input)
{
// here you can access session variables like you're used to:
Session["foo"] = input;
}
}
You could have all you pages derive from a BasePage class and put all of your util methods (or wrappers to them) into the base page class
If the class has state then leave it alone. Alternatively, take your state as parameters and then make it static.
You can access the Session variables using HttpContext.Current.Session[], and you can do this from any class (In fact, in many applications I have that use Session variables, I encapsulate all of my session variables in their own class).
Having said that, there is no way to have a method outside of a class, and there really isn't a [good] reason to do so.

Categories