Standalone functions in ASP.net - c#

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.

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].

Reusable Class Library Implementation

I've built a reusable Class Library to encapsulate my Authentication logic. I want to be able to reuse the compiled *.dll across multiple projects.
What I've got works. But, something about how I'm making the reference, or how my Class Library is structured isn't quite right. And I need your help to figure out what I'm doing-wrong/not-understanding...
I've got a Class Library (Authentication.dll) which is structured like this:
namespace AUTHENTICATION
{
public static class authentication
{
public static Boolean Authenticate(long UserID, long AppID) {...}
//...More Static Methods...//
}
}
In my dependent project I've added a reference to Authentication.dll, and I've added a using directive...
using AUTHENTICATION;
With this structure I can call my Authenticate method, from my dependent project, like so...
authentication.Authenticate(1,1)
I'd like to be able to not have to include that "authentication." before all calls to methods from this Class Library. Is that possible? If so, what changes do I need to make to my Class Library, or how I'm implementing it in my dependent project?
In C# a function cannot exist without a class. So you always need to define something for it, being a class for a static method or an object for an object method.
The only option to achieve that would be to declare a base class in the Authentication assembly from which you inherit in the dependent projects.
You could expose Authenticate as a protected method (or public works too), and call it without specifying the class name.
public class MyClassInDependentProject : authentication
{
public void DoSomething(int userId, long appId)
{
var success = Authenticate(userId, appId);
…
}
}
That said, you'll quickly find this to be a bad design. It conflates a cross-cutting concern with all sorts of other classes, and those classes are now precluded from inheriting from any other class.
Composition is a core principle of object-oriented programming, and we have the idiom "Favor composition over inheritance." This simply means that we break down complexity into manageable chunks (classes, which become instantiated as objects), and then compose those objects together to handle complex processing. So, you have encapsulated some aspect of authentication in your class, and you provide that to other classes compositionally so they can use it for authentication. Thinking about it as an object with which you can do something helps, conceptually.
As an analogy, think about needing to drill a hole in the top of your desk. You bring a drill (object) into your office (class). At that point, it wouldn't make sense to simply say "On," because "On" could be handled by your fan, your lamp, your PC, etc. (other objects in your class). You need to specify, "Drill On."
If you are making a class library in C# you should learn to use the naming conventions that exists: Design Guidelines for Developing Class Libraries
Here is how you should name namespaces: https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/interface
C# is also an object oriented language, hence the need of classes (using Authentication as you should name your class).
It also seems like the data source is hard coded. Your class library users (even if it's just you) might want to configure the data source.
Google about singleton and why it's considered to be an anti pattern today (in most cases).
You are obliged to use Class in order to invoke your method, just
When is static class just NameClass.Method
When is not static, you must create instance, ClassName ob = new ClassName(); ob.Method();
The format of a call like this is class.method, and you really can't escape using the "class" moniker even with the "using" designation. Something has to "host" the function.
I don't think what you are asking for is possible without using the base class method Jay mentioned. If all you want is to simplify the syntax whenever you call Authenticate() however, this silly solution (adding an extra method in each class that needs to do authentication) may be just what you want:
private static void DoAuth(long UserID, long AppID){
authentication.Authenticate(UserID, AppID)
}
If the ID's are always the same within some context, you could also overload it:
private static void DoAuth(){
DoAuth(1,1)
}
Yes, this does mean you have to add more code wherever you want to do the authentication (that's why it's silly! ;) ). It does also however, also reduce this:
authentication.Authenticate(1,1);
...into this:
DoAuth();
I leave the cost / benefit analysis of this up to you..
I know I am some 3 years late but here goes nothing.
To keep your code cleaner and more readable you should create a new namespace for all the re-usable code that you want to have. Then in that namespace have the Authentication Class and Authenticate Function.
To use this you can easily set a using on your namespace and use the function as you are doing like
Authentication.Authenticate()
But to use
Authenticate()
by itself you can always do
using MyNamespace.Authentication;
and in your code use Authenticate Function directly.

Call a function From Class file without creating Object of that class

I have created a function in a class. and i want to call it throughout my project. but i don't want to create the object of that class in every page. is there any global declaration for that class so that we can call in every page ? Inheritance is not possible in code behind file of aspx page .cs file.
You need to create a Static Method in your class so that you can call the function without creating an object of that class as shown in following snippet:
public class myclass
{
public static returntype methodname()
{
//your code
}
}
to call the function just use
//ClassName.MethodName();
myclass.methodname();
you can have look at MSDN: Static Members
Suggestion
One more resolution to your problem is to make use of SINGLETON DESIGN PATTERN
Intent
Ensure that only one instance of a class is created.
Provide a global point of access to the object.
You just need to make it a static method:
public class Foo
{
public static void Bar()
{
...
}
}
Then from anywhere:
Foo.Bar();
Note that because you're not calling the method on an instance of the type, there won't be any instance-specific state - you'll have access to any static variables, but not any instance variables.
If you need instance-specific state, you'll need to have an instance - and the best way of getting hold of an appropriate instance will really depend on what you're trying to achieve. If you could give us more information about the class and the method, we may be able to help you more.
Admittedly from what I remember, dependency injection in ASP.NET (pre-MVC) is a bit of a pain, but you may well want to look into that - if the method mutates any static state, you'll end up with something which is hard to test and hard to reason about in terms of threading.

Using Static method and variables - Good vs Bad

I am developing C# and asp.net web application.
I have general class called utilities, I have lot of public and static variables in this public utilities class.
Since this number is gradually increasing, I want to know is it good practice to store utilities methods and variable as public static.
Example of my code
public class utilities
{
public static string utilVariable1 = "Myvalue";
public static string utilVariable2 = "Myvalue";
public static string utilVariable3 = "Myvalue";
:
public static string utilVariableN = "Myvalue";
public static string UtilMethod1()
{
//do something
}
public static string UtilMethod2()
{
//do something
}
public static string UtilMethodN()
{
//do something
}
}
There's nothing inherently wrong with static classes, although they should typically not have state (fields). Your use of public static fields indicates that this is not the case, so it seems like you are using abusing the static keyword slightly. If your class needs to have state, then it should be a normal, non-static class, and you should create instances of it. Otherwise, the only public fields visible on the class should be const (consider the Math class, with constants such as Math.PI - a good use of static methods and fields).
Another consideration is cohesion. Methods typically exist grouped in one class because they are closely related in one way or another. Again, the Math class is a good example; everything in there has to do with maths. At some point, you would want to split your global utility class into multiple smaller, more focussed ones. See Wikipedia for some examples on cohesion, it sounds like your usage falls under "Coincidental cohesion (worst)".
There's nothing wrong with this approach for methods, but variables should really be const if they're going to be static and public. If they are subject to change then you should look at a different structure for variables that are being manipulated by more than one component.
Personally, I'm a fan of the Singleton pattern.
static is not a bad thing per se. Methods that don't need to access any member variables or methods should always be declared static. That way the reader of the code sees immediately that a method won't change member variables or methods.
For variables the situation is different, you should avoid static variables unless you make them const. Public static variables are globally accessible and can easily raise issues if multiple threads access the same variable without proper synchronization.
It is hard to tell for your case if it's a good or a bad idea to use statics, because you didn't provide any context information.
Creating one class to do it all is not a good practice, and it's recommended to structure your project, and keep stuff that belongs to each other separated from the randomness.
A great example of this was a project I took over from a co-worker. There was 1 class, called Methods. It contained over 10K lines of methods.
I then categorized them into approx. 20 files, and the structure was restored.
Most of the methods from that project were validating user input, which can easily be moved into a static class Validation.
One awful thing I notice is the mutable public and static variables. This is bad for several reasons:
Incorrect behavior, because if some method changes this, while it isn't supposed to do that, it causes other methods to behave improperly, and it's really hard to track down/debug.
Concurrency, how are we going to ensure thread safety? Do we let it over to all methods that work with that? Say if it's a value type, what will we let them lock on? What if some method forgets to make it thread safe?
Expand-ability (I hope you understand what I mean with that), if you have for example a static class data that stores all these public static variables, that you shouldn't have. It can store that once, if for example you might change your application structure a bit, and say want to make it possible to load two projects in the same screen, then it's very difficult to make that possible, because you can't create two instances of a static class. There is only one class, and it'll remain like that.
For number 3 a cleaner solution would be to store either a list of instances of a data class, or to store a reference to the default and/or active data class.
Static member, and private static members (or protected) are a good practice, as long as you don't make huge classes, and the methods are related.
Public and static variables are okay if they're not really variable.
The two ways to do this is by marking them constant (const modifier) or readonly (readonly modifier).
Example:
public class UtilitiesClass
{
internal UtilitiesClass() { }
public void UtilityMethod1()
{
// Do something
}
}
// Method 1 (readonly):
public static readonly UtilitiesClass Utilities = new UtilitiesClass();
// Method 2 (property):
private static UtilitiesClass _utilities = new UtilitiesClass();
public static UtilitiesClass Utilities
{
get { return _utilities; }
private set { _utilities = value; }
}
The advantage of method 1 is that you don't have to worry about thread-safety at all, the value can't change.
Method 2 is not thread-safe (though it's not difficult to make it that), but it has the advantage of allowing the static class itself to change the reference to the utilities class.
No, it is not a good practice for large applications, especially not if your static variables are mutable, as they are then effectively global variables, a code smell which Object Oriented Programming was supposed to "solve".
At the very least start by grouping your methods into smaller classes with associated functionality - the Util name indicates nothing about the purpose of your methods and smells of an incoherent class in itself.
Second, you should always consider if a method is better implemented as a (non-static) method on the same object where the data that is passed as argument(s) to the method lives.
Finally, if your application is quite large and/or complex, you can consider solutions such as an Inversion of Control container, which can reduce the dependency on global state. However, ASP.Net webforms is notoriously hard to integrate into such an environment, as the framework is very tightly coupled in itself.

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

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.

Categories