This question already has answers here:
Static vs non-static class members
(7 answers)
Closed 5 years ago.
I have been having a hard time deciding when I should declare a class filed as static.
I got the idea that a static field is shared among all objects created from a class, unlike a regular non-static field, which is held by each of the objects.
Then if it is known that only one object will be created from a class (because I have seen such cases many times), what is the meaning of a static field?
If the definition of "static" is "shared among all instances," does a static field serve the same role as a regular non-static field, provided there is only one object created from the class?
I got this old project from my boss to study C#, and I see some fields declared as static in a class, but there is only one object created from the class, and I am a bit confused what the point is if it does not have multiple instances.
You should not decide to use static just because there´s only one single instance. As you´ve already mentioned there is an instance.
The question if something should be static depends on if your member depends on an internal state, that is do you need to set some property befpore you can incoporate with this member. So even if there´s just one single instance existing this instance shares a set of members defining its state. Only when your member could omit all those information from that single instance it should be marked static.
However making some member static makes many things - e.g. mocking - quite hard as you create a heavy dependency on your class holding that member
Related
This question already has answers here:
Multiple Inheritance in C#
(13 answers)
Closed 4 years ago.
All similar questions I've looked though here, mentions multiple interface inheritance. However, I am not sure how MII could be a workaround to the problem.
Lets say, I have two library class (My_Class_1 and My_Class_2) of different methods. Then I want to create a new class, that can use both of these classes' methods natively, like:
public class My_Application : My_Class_1, My_Class_2 {
public My_Application(){
method_from_Class1();
smth_property_declared_in_My_Class_2 = "hello";
}
}
However, that is not possible with C#. What are flexible workarounds, to extend/enrich class with other classes? In PHP, that is unbelievably simple, just in the top of the class we can:
use example_trait_1;
use example_trait_2;
I would rather not use interfaces; in my view, they have no relation to solving this problem.
p.s. I don't want to create initialize objects for those classes. I want them to be native part of the application class.
As others mentioned, it isn't possible (because that's not what inheritance is), but it seems one workaround would be to have a public property of type Class1, inside a class that inherits Class2.
That also gets around the problem of "which class am I looking at now?" since you'd need to explicitly mention the property when you want something of type Class1.
And if you need to modify Class1 first, then you just create a separate class that inherits Class1 first, then have the public property be of that new type.
This question already has answers here:
Is there an easy way to make an immutable version of a class?
(7 answers)
How do I create an immutable Class?
(8 answers)
Closed 5 years ago.
I want to see if I can make an instance of a class immutable even if the class itself isn't. What I have here is a similar situation to IntPtr.Zero and other static fields like that, except it's a mutable class and not a struct.
class TestClass
{
public static readonly TestClass GoldStandard = new TestClass();
public int field = 0;
}
class Program
{
static void Main(string[] args)
{
TestClass test = TestClass.GoldStandard;
test.field = 1; // I want to keep this from happening.
Console.WriteLine(TestClass.GoldStandard.field);
}
}
What can I do to keep GoldStandard from being modified?
EDIT: I regret that my question was so badly misunderstood. This is clearly not a duplicate of Immutable type and property in C# or How do I create an immutable Class?. Those questions are about how to create an immutable class, and not how to create an immutable instance of a mutable class.
As for Is there an easy way to make an immutable version of a class?, it certainly sounds very similar to my question. However, there are some important reasons it shouldn't count.
The question asks how to make an instance immutable at some point during the instance's lifetime, rather than just having one instance of a mutable class be immutable from the start.
The question asks how an immutable second class can be generated to mimic a mutable class, rather than having one mutable class act as immutable in a specific case.
The answer to the question doesn't even address my question at all, and is mostly about how immutable classes work in general.
I understand moderators can't take too much time to understand the questions in depth when they're scanning for duplicates, but I hardly think it's fair for my question to be closed as a duplicate because of such superficial similarities.
This question already has answers here:
When to use static classes in C# [duplicate]
(11 answers)
Closed 9 years ago.
I am a C++ programmer who makes a switch to C#.I was said not to use static classes.
I understand that in C# if the class has only static members it should be static.(My class has only static members)
Can you please explain me what could be a problem using static classes?
When we really should use them?
Thanks
The main reason is that sometimes (but NOT always), it's better to use a singleton class, because a singleton class can implement interfaces.
Static classes have no difference from non-static classes apart from the fact that you can't instantiate static classes (because they're static of course) and this static class will not be able to take advantage of cool OOP features such as inheritance (it can't be subclassed in C#).
The main thing you have to be aware of when a static class contains static members is making the class static members thread-safe if used by multiple threads.
Can you please explain me what could be a problem using static classes? When we really should use them?
If your class only exposes static members then you can make it a static class, but only if you are sure you will not need instances of this class. In fact, there's absolutely no issues in using static classes, just make then thread-safe (if required) and make sure it fits in with your system's design.
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated.
http://msdn.microsoft.com/en-us/library/79b3xss3.aspx
Check also this link:
When to use static classes in C#
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have a bunch (may be 10 to 15 ) methods in my C# code all of which are 'Static'. Obviously, all of them are called with the ClassName. All works well. But, are they any advantages/disadvantages of using them that way? or would I get any performance benefit if I do not use 'Static' for my methods?
Technically there is slight performance benefit when you are using static method, because you don't need to load instance reference to stack when executing method. But that is really minor optimization which you will not notice.
From programming point of view static methods are hard to mock and they introduce strong coupling with implementation in your code. Also you lose benefits of abstraction and polymorphism when use static methods.
You can make static private methods from instance methods which don't use instance data. But public static methods usually give you problems with mocking and dependency injection, so usually I avoid them. One exception is factory methods which used to create instances of class - Loan.CreateLongTermLoan (thus you can't have constructor with custom name in C#, but you want some descriptive name which describes details of created instance) or Loan.Parse.
If you're worrying about the performance benefit of static methods over instance methods then you're micro-optimizing and without doubt prematurely optimizing. You should worry about good class design before you worry about this sort of thing!
If you've got methods that don't operate on the state of an instance then they are good candidates for being static methods. For example, factory methods are an obvious use of static methods.
If you've got methods that operate on the state of the instance then they need to be instance (non-static) methods. For example, a method that changes a member variable could not be static.
FYI : At the IL level all instance methods are called via a CallVirt instruction, even if they are not virtual. This allows the runtime to generate a NullReferenceException if you call a method on a null reference. A static method is called via the Call instruction.
No performance benefit for being static or not.
If you don't need an instance of the class in a method, then it's a candidate for being marked as static.
The problem with static method comes the moment you need a sub-class.
Static methods cannot be overridden in sub-classes, hence your new classes cannot provide new implementations of the methods, making them less useful.
It's a conceptual question. Does the method …
belong to a specific instance? Then it's not static.
belong to the class rather than to a specific instance? Then it's a prime candidate for being static.
Note that static methods can't access instance members (non-static members) of an object.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to know whether my understanding on the constructors is correct or not. I just tried to attempt a quiz for constructors but confused whether my understanding is correct or not
--> Every class needs at least one constructor defined - False (In C#, if you don't provide one, the compiler automatically provides a default constructor.)
--> It’s possible to avoid a class being instantiated by simply having only a private constructor on it. – False (A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.)
--> A static constructor in a nonstatic class is called once on each object creation. – False (If a static constructor has been called once, compiler will not call it again, it will get called once only .The execution of a static constructor is triggered by the first of the following events to occur within an application domain: 1. An instance of the class type is created. 2. Any of the static members of the class type are referenced.)
-->You can specify on the constructor which classes of interfaces that class is inheriting
( i don't know please clarify )
--> Every class needs at least one constructor defined - False (In C#, if you don't provide one, > > the compiler automatically provides a default constructor.)
- Your understanding is Correct
--> It’s possible to avoid a class being instantiated by simply having only a private constructor on it. – False (A private constructor is a
special instance constructor. It is generally used in classes that
contain static members only. If a class has one or more private
constructors and no public constructors, other classes (except nested
classes) cannot create instances of this class.)
- You can have a private constructor, in which case other classes cannot create instance of it (but why will you do that?)- People do that to put some control in object's instantiation, as what they do commonly in some design patterns. In a nutshell, you can still create an instance of a class with private constructor thru some other means (e.g. from static methods).
--> A static constructor in a nonstatic class is called once on each object creation. – False (If a static constructor has been called
once, compiler will not call it again, it will get called once only
.The execution of a static constructor is triggered by the first of
the following events to occur within an application domain: 1. An
instance of the class type is created. 2. Any of the static members of
the class type are referenced.)
- Your understanding is Correct
-->You can specify on the constructor which classes of interfaces that class is inheriting ( i don't know please clarify )
- False, You specify in the class declaration itself the interfaces or classes that the class is going to inherit not in the constructor