Regarding Static class in c# [duplicate] - c#

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
When to Use Static Classes in C#
why anyone would write a static class. we can declare a static method in any class and just call that method without creating class instance. so please tell me in what type of situation a person would create a static class and also tell me what are the main differences between static class and normal class.
thanks

A static class cannot be instantiated. It's main uses are to make it clear that the class has no instance methods and to prevent people from accidentally trying to "new" the class.

Generally I would advise you not to write static classes.
There are cases where you want them though
Extension methods have to live on static classes. This is the best reason to have a static class.
If you do have a bunch of static methods that don't make sense as extension methods and don't fit into your object model then there might be room for a collection of static methods. This is particularly the case when you cannot redesign your app.
Sometimes this happens because you are dealing with some 3rd party stuff that you cannot change. Then if you end up with a class with only static methods on it - you should make it static since anyone creating an instance is clearly not understanding what you have done.
Having said all of that for the most part my advices is avoid static methods, classes and data. I am not saying never use them - just try not to.

A static class cannot contain any constructors, only a static constructor that is called first time one of its members is accessed.
That is basically the difference. Performance wise we also get another for free by the compiler since it can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are also sealed and therefore cannot be inherited.
http://msdn.microsoft.com/en-us/library/79b3xss3(v=VS.100).aspx
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type.
Another valid point is that Extension Methods has to be declared in a static class
http://en.wikipedia.org/wiki/Extension_method
The new language feature of extension methods in C# 3.0, however, makes the latter code possible. This approach requires a static class and a static method.

In static class all method all static. we can not declare normal method in static class.
differences between static class and normal class.
We can not create object of static class, when we use method of static class just use classname.MethodName but in normal class we have to first create object of class then we can access method of normal class.
static class ex.
Class1.functionname();
normal class ex.
Class1 cs = new class1();
cs.functionname();
functionname should not be private.

The difference is that you can't instantiate a static class. So you'd make a class static if you don't want it ever being instantiated. This is useful in cases when you're dealing with threading issues, and you want all threads to be guaranteed to use the same instance of your class.
A more philosophical scenario is when you have a class that doesn't need to be instantiated, such as (for example) you're building a database application and you create one class to do all the database access stuff. It's basically just a collection of methods. Then making the class static simply becomes a step to make your design more consistent.

Related

What is the point of a non-static method in a static class?

I took a look over this question and I was wondering the opposite situation. Why would be needed?
Someone said there that:
Why would you have a "shared method" that is in a class, not in a
module? Answer: To share it amongst instances of its class.
Well this it is clear why it would be necessary to use a static method within a non-static class. What about the opposite?
The opposite (instance method in static class) is impossible, at least in C#. It produces compile time error.
In Java, static methods work the same way in nested static class as they do in non-nested non-static classes.
In the example given the main(String[] args) has to be static
If you have a method which doesn't use this it is preferable (and simpler) to make the method static so its clear the method doesn't need an instance.
A class can only be declared static when it is a nested class - you do that when you want that nested class to be accessible without having to create an instance of the containing class.
Apart from that, it is just a normal class, which can have an instance state (non static variables) and you would use non static methods in that class like you would in any other class...
For example, HashMap contains a static nested class Entry which has some non-static methods.
ps: you just added the C# tag - my answer relates to your original question, tagged Java.
Static class cannot be instantiated so there is no use of declaring non static methods inside a static class.

Best way to prevent a class from being Instantiated?

I need to know how to prevent a class from being Instantiated in .net?
I know few methods like making the class Abstract and Static.
Is there any more way to achieve this?
Making the class static is the best approach, if you absolutely don't want any instances. This stops anyone from creating instances. The class will be both sealed and abstract, and won't have any constructors.
Additionally, the language will notice that it's a static class and stop you from using it in various places which imply instances, e.g. type arguments and variables. This indicates the intention more clearly than just having a private constructor - which could mean that there are instances, created within that class (e.g. for a singleton implementation).
Oh, and making the class static will stop you from introducing any pointless instance members in the class, too :)
See MSDN for more information about static classes.
Mark the constructor(s) private, protected or if in used from another assembly, internal
Marking the constructor private. Of course, this doesn't prevent the class from instantiating itself through a static method, for example...
More practically, what's the purpose of disallowing class instantiation. If it's to have a singleton, then a private constructor is appropriate. If it's to force subclassing, making the class abstract is better; if it's to have a class with utility methods, making it static is one way (then you can only have static methods).
I need to know how to prevent a class from being Instantiated in .net?
Your question is not clear.
Do you mean instantiated at runtime? Make the class abstract or static.
Do you mean that the constructor is not accessible in code? Make the constructor private. But note that someone could still use reflection to grab a handle on a constructor and instantiate an instance at runtime.
So, which do you mean?
If the question is:
How can you make your class not be instanced without having your class
be static or abstract?
Then the answer to this is to implement the singleton pattern, which in .NET 4+ this is done easily with:
public sealed class myClass
{
private static readonly Lazy<myClass> lazyInstance =
new Lazy<myClass>(() => new myClass());
public static Instance
{
get
{
return lazyInstance.Value;
}
}
private myClass()
{
// constructor logic here
}
}
The singleton pattern allows you to pass your class around as a reference to methods, while still ensuring that you have only a single instance of your class. It also makes testing much easier as you can have a ImyClass instance which myClass implements, this is very helpful when making mock objects.
Without .NET4 you can still implement the singleton pattern, for example:
private static readonly myClass instance = new myClass();
public static Instance
{
get
{
return instance;
}
}
// rest of code remains the same
Which doesn't have deferred loading until it's called, there's lots of other ways as well (I think about 6 different ways), but the above two are the most common ones.
In summary the question is likely asking if you know the singleton pattern and if you recognise it's importance over static classes for unit tests and mock objects.
As others have already pointed out, static fields, even those marked readonly can be set with reflection, in addition the private constructor can be called using reflection. If you need to prevent these, either you need to make the calling code run in a less trusted app-domain space, or you will need to implement your class as static.
Generally though, people don't bother with such levels of reflection to get around your constraints unless they 'really need to' for example, writing obscure / extreme fringe case unit tests.

C# static class why use? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to Use Static Classes in C#
I set my classes as static a lot, but I am not sure when use static or not, or what's the difference it makes to use it or not.
can anybody explain please?
Making a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.
If a class is declared as static then the variables and methods need to be declared as static.
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
->The main features of a static class are:
They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates on data when an object is created.
Example
static class CollegeRegistration
{
//All static member variables
static int nCollegeId; //College Id will be same for all the students studying
static string sCollegeName; //Name will be same
static string sColegeAddress; //Address of the college will also same
//Member functions
public static int GetCollegeId()
{
nCollegeId = 100;
return (nCollegeID);
}
//similarly implementation of others also.
} //class end
public class student
{
int nRollNo;
string sName;
public GetRollNo()
{
nRollNo += 1;
return (nRollNo);
}
//similarly ....
public static void Main()
{
//Not required.
//CollegeRegistration objCollReg= new CollegeRegistration();
//<ClassName>.<MethodName>
int cid= CollegeRegistration.GetCollegeId();
string sname= CollegeRegistration.GetCollegeName();
} //Main end
}
Static classes can be useful in certain situations, but there is a potential to abuse and/or overuse them, like most language features.
As Dylan Smith already mentioned, the most obvious case for using a static class is if you have a class with only static methods. There is no point in allowing developers to instantiate such a class.
The caveat is that an overabundance of static methods may itself indicate a flaw in your design strategy. I find that when you are creating a static function, its a good to ask yourself -- would it be better suited as either a) an instance method, or b) an extension method to an interface. The idea here is that object behaviors are usually associated with object state, meaning the behavior should belong to the object. By using a static function you are implying that the behavior shouldn't belong to any particular object.
Polymorphic and interface driven design are hindered by overusing static functions -- they cannot be overriden in derived classes nor can they be attached to an interface. Its usually better to have your 'helper' functions tied to an interface via an extension method such that all instances of the interface have access to that shared 'helper' functionality.
One situation where static functions are definitely useful, in my opinion, is in creating a .Create() or .New() method to implement logic for object creation, for instance when you want to proxy the object being created,
public class Foo
{
public static Foo New(string fooString)
{
ProxyGenerator generator = new ProxyGenerator();
return (Foo)generator.CreateClassProxy
(typeof(Foo), new object[] { fooString }, new Interceptor());
}
This can be used with a proxying framework (like Castle Dynamic Proxy) where you want to intercept / inject functionality into an object, based on say, certain attributes assigned to its methods. The overall idea is that you need a special constructor because technically you are creating a copy of the original instance with special added functionality.

what is difference making full class static and making functions of the class as static

Hello All:
what is difference making full class static and making functions of the class as static?
I mean are there any performance issues?
The feature of static classes was only introduced in C# 2. The CLR doesn't really have such a concept. A static class in C#:
Has no constructors, not even a default parameterless one
Is sealed: it can't be subclassed
Is abstract: you can't create instances of it (which also follows from there being no constructors)
Can only contain static members
Can't be used as a parameter or variable type or a generic type argument etc.
Can't specify any base type other than object
There's no performance difference between using static members of a "normal" class and using ones in a static class. It's primarily a way of stating the intention that there should never be any instances of this class, without having to provide a private and never-called constructor, and forcing the compiler to check that you're not trying to use it as a normal class.
Note that extension methods (introduced in C# 3) can only be declared in a top-level, non-generic static class.
It has two implications:
All methods of the class must also be static.
You can't make an instance of that class other places in your code.

Static Method of a Static Class vs. Static Method of a Non-Static Class ( C# )

I was asked the above question in an interview. Could you please explain the differences? ( performance - memory - usage - when to use which ? )
Thank you,
Erkan
Declaring a static class documents your intent for that class to be a collection of static functionality, and anyone adding instance members will get a compilation error.
A non-static class with static members usually indicates that the class is designed to be instantiated at some point. Static methods of these classes usually do one of two things:
Provide a factory method for creating an instance of that type;
Provide helper functionality that does not require an instance of the type;
Also, as mentioned already, extension methods can only be declared on a static class.
I assume you were asked for the differences?
A static method on a static class can be used to define an extension method. A static method on a non-static class cannot.
In terms of performance and memory usage; precisely nothing. Having a static class means you know there are no instances, but back in 1.1 having a private constructor sufficed. Use a static class if it simply makes no sense to have an instance! (utility classes etc)
When you are providing utility functions and all your methods are static, I recommend you use static methods in a static class.
When you want to provide utility methods that just deal with your instance, I recommend you use static methods in a non-static class. For example:
var myClass = MyClass.Create();
var myClass = MyClass.Parse("serialized.MyClass");
In terms of memory, there is a slight difference: the static method in a non-static class will be allocated only when the first instance of that type is created, and deallocated when the last instance of that type is deallocated. Static methods on instance objects are very useful when we have collections of objects of the same type in order to decrease the amount of memory used. The drawback of using static methods is that they are not unit testable, so before creating a static method, an eye should be kept on how it will affect the code coverage.
One major difference I faced when deciding whether to go with normal class with all static methods or, use a static class, is that a normal class supports interface implementation, where as static class does not.
I use static class only when I am sure it will be a collection of static functions (usually helper functions), and will never be in the main stream of program. I promote interface programming, for dependency injections, unit testing etc. So, for main flow of program, I use normal class with static methods.
Ref: MS Docs

Categories

Resources