What is the benefit of using Static classes? Why would you use it? Why not create a standard instiatable class (new keyword) and have functions in that to do the same job as a static class?
MVP 2007-2010 any chance of a regain?
Professional Software Developer and Infrastructure Engineer.
Static classes can be used/accessed from anywhere in the project without actually declaring a new instance of it. Now for when to use them ....
Say you have a class that returns the brand name of your car as an example, it really isn't associated with an object, so there is no reason to the unnecessary and create an instance. So you would just do this instead...
C# Code:
static class CarTypeInfo
{
public static string GetCarType() { return "cartype"; }
//etc..
}
instead of...
C# Code:
class CarTypeInfo
{
public string GetCarType() { return "cartype"; }
//etc..
}
Also note a static class can only contain static methods
thanks. i am aware of how to use them and the declaration but just wondered why you would use it, what the benefit is. I know the CLR will automatically load the static classes since it doesnt require for it to be instantiated hence improving performance slightly.... but still overall the concept i dont quite get. Perhaps ideal for say using it as a "helper" class where you can pass in an object to update to SQL. example:
public static class DataHelper {
public static bool UpdateAccount(Account accountToUpdate)
{
//SQL Stuff here
}
}
MVP 2007-2010 any chance of a regain?
Professional Software Developer and Infrastructure Engineer.
It's useful for when you don't need a class, just a method to do something.
For example, why should I have to create an instance of a Convert class if all I want / need to run in the ToDouble method it contains? The concept of static is in VB.Net and has been in C++ for a while as well other languages so it's a useful construct.
KrisSiegel.com - My Personal Website with my blog and portfolio Don't Forget to Rate Posts!
I don't know if this is true in C#, but if you have ever written in VB.NET, and have used a module (as opposed to a class) to hold some common data, or common functions, then you are using static members.
I have often wondered what is the true benefit of static classes.
They can't be inherited....
Why make a whole class static for one method...you can declare a static method in a public class....
I would be led to think the only purpose is to hold common values: variables, properties, etc. I would say not to use a static class for an object that you want throughout the application, because a static class really isn't an object and that is what the singleton pattern is for.
That would be a restriction/limitation (depending on your point of view) to the .net languages: all methods must be contained within a class.
Whilst you certainly could drop them into an externally visible non-static class, you would (by default) still be able to create an instance of that class. Bit pointless, eh? In versions below 2.0, you would add a private default constructor to prevent instantiation: 2.0 added the ability to mark the class as static to allow you to skip that step.
From a slightly lower level of detail... Using the VS2008 C# compiler on the following class:
Code:
namespace Sandbox
{
public class StaticSample
{
public static void FooBar()
{
Console.WriteLine("Hello world");
}
}
}
The IL is as follows; notice the constructor that was generated:
.class public auto ansi beforefieldinit Sandbox.StaticSample
extends [mscorlib]System.Object
{
.method public hidebysig static void FooBar() cil managed
{
// Code size 13 (0xd)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "Hello world"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
} // end of method StaticSample::FooBar
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method StaticSample::.ctor
} // end of class Sandbox.StaticSample
Marking the class as static:
.class public abstract auto ansi sealed beforefieldinit Sandbox.StaticSample
extends [mscorlib]System.Object
{
.method public hidebysig static void FooBar() cil managed
{
// Code size 13 (0xd)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "Hello world"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
} // end of method StaticSample::FooBar
} // end of class Sandbox.StaticSample
Also worth noting - 3.0+ have extension methods - required to be static for good reason. Creating a single class for a single method (see the "limitation" comment in the first paragraph) is entirely up to the person writing the code.
Apart from synchronisation objects and other private members, I wouldn't condone using static variables - fair asking for trouble; there are other means of maintaining state application wide - thread context, web context, etc.
As to the singleton pattern - from a coder's perspective, I would positively hate having to write Convert.Instance().Insert method here. From a pattern perspective, it's used when you wish to restrict instantiation. As you can see, marking a class as static means you can't instantiate a static class. Static classes also make good simple factories, or mediators.
I don't know if this is true in C#, but if you have ever written in VB.NET, and have used a module (as opposed to a class) to hold some common data, or common functions, then you are using static members.
They are shared members, im pretty sure they are at the least
But one thing i have noticed with modules is that if i add one project to another and try to access a member from the other projects module, it won't work but with a class it will. So in the end they do have there benefits.
They are shared members, im pretty sure they are at the least
But one thing i have noticed with modules is that if i add one project to another and try to access a member from the other projects module, it won't work but with a class it will. So in the end they do have there benefits.
That's not true. A Public member of a Public module is accessible outside an assembly just the same as Public members of Public classes. When compiled a module is implemented as a class so you ARE accessing a member of a class when you access a member of a module.
This is all really simple. Static members are members that logically belong to a class and not an instance of that class. If every member of a class is like that then it is logical to declare the class static too. You don't have to, but it's logical. A static class is basically a collection of utility functions, generally all related to one area of functionality.
Take the File and Directory classes in the .NET Framework for example. Nobody every creates a File object or a Directory object. All useful members of those two classes are static. As such it would have been logical to declare the classes themselves static. The authors chose not too for whatever reason. In fact, I don't think there's a static class in the Framework. That said, if creating an instance of a class cannot possibly be useful, as in the File and Directory classes, then declaring the class static is logical.
I don't believe it is, i have tried everything and it never works.
VB Runtime functions like MsgBox and InStr are declared in modules in the Microsoft.VisulaBasic.dll assembly. The fact that you can call them in your own code is proof enough.
Have you actually declared your module(s) public? Classes are Public by default but modules are Friend by default, so you have to add the Public key word yourself. That's because modules should generally not be exposed publicly.
Last edited by jmcilhinney; Feb 9th, 2008 at 02:01 AM.
Yes thats what i do of course, it just never works. Those modules in the assembly could have been in a different language though?
That makes no difference. All assemnlies are in MSIL. The language they were developed in makes no difference. If you reference an assembly in C# that was written in VB then any public modules will simply be seen as classes, because that's exactly what they are compiled as.
I have attached a VS 2005 solution to this post. It contains a VB application, a C# application, a VB library and a C# library. Both applications have references to both libraries and both applications are able to access members of the C# class and the VB module. I don't know what you're doing wrong but public is public.
I'll leave this topic alone now because it's well of the original topic of this thread.
If I get the idea of Static classes right, then it would mean that that code Paul M posted...
C# Code:
static class CarTypeInfo
{
public static string GetCarType() { return "cartype"; }
//etc..
}
Can simply be used like this?
C# Code:
CarTypeInfo.GetCarType();
Without needing to make an instance of the class, like so?
C# Code:
CarTypeInfo myCar = new CarTypeInfo;
(I'm rather new to C#, so this code might be off, but you'll get the idea).
It's not a case of not needing to create an instance. It's the case that you specifically do not creat an instance. Static members aren't members that have a handy feature of not needing an instance to be created. They are specifically members of the class and not members of an instance, so they are called on the class and not on an instance. Your code is correct but your logic is not quite right.