Is Calling static in c# as in my example safe to do? - c#

I've have several simple helper methods that I've put in a utils.cs class. An example is one below. I call this from an asp.net controller which means that there could be many calls happening on many threads around the same time.
I realize I do this because resharper suggests making the method in the class static but I'm worried maybe that's the wrong thing to do and maybe I should new up the Utils class every call.
Thoughts?
public class Utils
{
public static List<Speaker> FilterSpeakersByTenant(List<Speaker> inSpeakers, string tenantName)
{
return
inSpeakers.
Where(speaker => speaker.Sessions.
Any(a => a.TenantName == tenantName)).
ToList();
}

If you do not access global/shared state in your static method then it should be fine...
The only multithreading problem may arise when you access your parameters (e.g. the list) in concurrent threads.
If the class does not have any state (i.e. member variables or properties) it does not make a difference whether you instantiate the class or use a static method.

Resharper suggests that you make it a static method because it does not access any instance members. Since you also don't access any static data you are safe from multithreading issues as well.
So long as you don't add any static or non-static fields that the method will use, there's no downside to making it static.

It is fine. A non static class can inherit from an interface. You do not need seem to need that here. A non static class can be used to create multiple objects with multiple states. You also do not need that.

The method is completely thread safe. It doesn't use any shared state, and it doesn't modify the parameters.
For better readability, consider changing your method to an extension method on IEnumerable<Speaker>:
public static IEnumerable<Speaker> ByTenant(this IEnumerable<Speaker> source, string tenantName)
{
return source
.Where(speaker => speaker.Sessions.Any(a => a.TenantName == tenantName));
}
Then you can use it as
var filteredSpeakers = speakers.ByTenant(tenantName).ToList();

Safe is such overrated concept, is not it? :).
The problem is, that it is not a thread safe method because the input data:
List<Speaker> inSpeakers
can be changed in same time as it is enumerated by LINQ Where operator, it would throw a exception because otherwise there would be race condition.
If you are certain, that the method gets only copy of original list, then OK, but I do not see such guarantee here. List are used to add/remove items and access them.
Other ways to handle thread safety is locking, which has performance side effect in case of high contention.
Little better would be array, number of items can not be change.
Very good idea would be ImmutableList.
And if you are actualy looking for way to share state in list between many threads, then some concurrent collletction would be best case.

Related

Static methods/class vs non static [duplicate]

I'm new to c sharp and programming generally. I have a quick question - what is best practise with regards to static/non static variables.
I have a variable,private int x, which belongs to class y. To access this variable, i need to reference y. If x was static however, i can access this variable with no references to y.
Which is the best way to go, in a situation whereby several methods within the class y will be referencing this value ?
Hope this makes sense, and my question isn't too basic !
Many thanks
You need to think about static variables as belonging to the class, not to instances of the class.
If, in all instances of the class this variable should be identical, use a static variable.
If not, use an instance variable.
In general having public static variables is bad practice - it is a shared global resource and if you change it you need to synchronize access to it. Having global state is something you want to avoid as much as possible.
Best practice is to avoid public static. In OOP, class is meant to hide its members. Static is actually not a member of the instance but of the type.
Static comes handy if you are implementing singleton pattern. But then again they need to be made private and accessible through a public property.
You need to read Static Classes and Static Class Members (C# Programming Guide).
Well I can't conclusively say that one is better, because they serve different purposes.
Are you familiar with OOP? In OOP, static objects or members of a class that can be accessed directly from the class, while non-static members can only be accessed from the instance it belongs to.
C# follows a similar principle for the methods. The static methods can by accessed directly from the class, while non-static methods (or instance methods as I like to call them) have to be accessed from an instance. That is why instatiating needs to be done for instance methods, while for static methods it's just not needed, and furthermore impractical (see below).
In OOP, static variables are used for values which cannot be stored by an instance variable. Example: supposed you wanted to keep a count of how many instances of a class exists? How would you store that in a single instance?
The methods use a similar principle. They should be used for procedures for which it is impractical to do within an instance of a class. I tend to use them for broad procedures (not a technical term), meaning those that do not require me to instantiate an object. Example, adding two parameters. (This usage may or may not be correct, but I believe it is)
However, if you wanted to add two properties of an object, the method cannot be static, because as you would soon realize, static methods cannot access instance methods or variables within a class. Of course that makes sense because that static method would not know which instance of the class the get these from unless it were told, since it is not part of an instance itself)
For the sake of no further complicating things, I'll stop here. Let me know if you misunderstood anything.
Your choice depends on your architecture.
Static makes part of a Type, others make part of an instance of that type. If you want have some shared state (say) between different instances of the same type, use static. If you want that every instance have it's own value, independent from others, use instance fields.
In both cases, by the way, avoid to expose like a public fields, but use properties.
I completely agree with Mr Oded:
If, in all instances of the class this variable should be identical, use a static variable.
If not, use an instance variable.
Yes, adding static to a class member basically means you can access it without an instance, and only outside any instance. And yes, it becomes a global resource, or even a global variable if you will.
But I think there's at least another (heavily edited) good point to be made here...
Using static members as global vars go against OOP
This means once you set a static member you can't pass it around as an object. The more you use static as global var, the more difficult it is for unit testing / mocking classes.
There is a solution for that, Singletons. But they should never come without warnings!
At other hand, if you're sure you really need global vars, take a look at the Toolbox pattern. It's a not well known extension of Singleton pattern. It's so unknown in fact, if you google for it you won't find it with those keywords (toolbox pattern).
So plan ahead. Read more. Get to know about every option so you can decide better. Even get a book. Object Oriented Programming is more about applying concepts that will help in the long run than just making things work now.
In general if you want to have a variable public, either static or instance, you must wrap it in a property and expose it like that. This is for sure a principle that you will love to follow.
But despite some of the other answers I cannot say don't use static. Static is not the devil that you should avoid in any case. What you have to do will decide if you are going to use static or not, as long as you keep your program clean and easy to maintain.
Easily speaking, and not in the language of the elders, static stands for something that don't belong to any instance of this class but has an effect on them. An example of a static property in a class that generates instances is for example a factor, which should be global for all instances of the class, to take part in a calculation that is done inside instances. To this case, and to my opinion, it is better to have this factor declared as static rather that have it in every single instance. Especially if this factor changes in the lifetime of your program to affect the next calculation.
You need to ask a question to youself: why I need x to be static?
If you make x static it means that x is a part of all objects of class A, but when x is not static it means, than x is a part only of one object.
In geleral using of static fields is painfull for bug tracking, but in some cases this is very helpfull.
I suggest you to look in using of singelton http://en.wikipedia.org/wiki/Singleton

Designing a Thread Safe Class

When reading the MSDN documentation it always lets you know if a class is thread safe or not. My question is how do you design a class to be thread safe? I am not talking about calling the class with locking I am meaning I am working for Microsoft create XXX class\object and I want to be say it is "Thread Safe" what would I need to do?
The easiest and most foolproof way of making a class thread safe is to make it immutable. The beauty of it is that you don't ever have to bother with locking again.
Recipe: Make all instance variables readonly in C# (final in Java).
An immutable object, once created and initialized in the constructor, cannot change.
An immutable object is thread safe. Period.
This is not the same as having a class with only constants.
For mutable parts of your system, you still need to account for and handle locking/synchronization property. This is one reason to write immutable classes in the first place.
See this question as well.
In addition to the other excellent answers here, consider another angle as well.
It isn't enough that the internal data structure of the class is 100% thread safe if the public API has multi-step operations that cannot be used in a thread-safe manner.
Consider a list class that has been built such that no matter how many threads are doing no matter how many types of operations on it, the internal data structure of the list will always be consistent and OK.
Consider this code:
if (list.Count > 0)
{
var item = list[0];
}
The problem here is that between the reading of the Count property and the reading of the first element through the [0] indexer, another thread might have cleared out the contents of the list.
This type of thread safety is usually forgotten when the public API is created. Here, the only solution is for the calling code to manually lock on something on each such type of access to prevent the code from crashing.
One way to solve this would be for the list type author to consider typical usage scenarios and add the appropriate methods to the type:
public bool TryGetFirstElement(out T element)
then you would have:
T element;
if (list.TryGetFirstElement(out element))
{
....
presumably, TryGetFirstElement works in a thread-safe manner, and would never return true at the same time as it is not able to read the first element value.
To state that the class is thread safe, you are assserting that the internal data structures in the class won't be corrupted through concurrent access by multiple threads. To make that assertion, you would need to introduce locking (synchronize in Java) around critical sections of code within the class which could potentially lead to corruption of they were executed by multiple concurrent threads.
Thread safe classes is all about protecting the data (instance variables) in your class. The most common way to do that is to use the lock keyword. The most common newbie mistake is to use lock the entire class instead of a more finegrained lock:
lock (this)
{
//do somethnig
}
The problem with that is that it can give you a major performance hit if the class does something important. The general rule is to lock as little as possible as short time as possible.
You can read more here: lock keyword in C#
When you have strarted to understand multithreadnig more deeply you can also take a look at ReaderWriterLoch and Semaphore. But I suggest you only start with the lock keyword.
The documentation doesn't suggest that classes are thread-safe, only methods are. In order to assert that a method is thread-safe, it has to be callable from multiple threads simultaneously without giving incorrect results (where incorrect results would be the method returning the wrong value or the object getting into an invalid state).
When the documentation says
Any public static (Shared in Visual
Basic) members of this type are thread
safe.
it probably means that the static members of the class do not mutate shared state.
When the documentation says
Any instance members are not
guaranteed to be thread safe.
it probably means that methods have minimal internal locking.
When the documentation says
All public and protected members of
this class are thread-safe and may be
used concurrently from multiple
threads.
it probably means that all methods you can call use the appropriate locking within them. It is also possible that the methods do not mutate any shared state, or that it is a lock-free data structure that by-design allows concurrent usage without any locks.
non generic ICollection classes provide properties for thread safety. IsSynchronized and SyncRoot. unfortunately you cannot set IsSynchronized. You can read more about them here
In your classes you can have something simlar to IsSynchronized and Syncroot , expose public methods/properties alone and inside method body check for them. Your IsSynchronized will be a readonly property, so once your instance is initialized, you will not be able to modify it
bool synchronized = true;
var collection = new MyCustomCollection(synchronized);
var results = collection.DoSomething();
public class MyCustomCollection
{
public readonly bool IsSynchronized;
public MyCustomCollection(bool synchronized)
{
IsSynchronized = synchronized
}
public ICollection DoSomething()
{
//am wondering if there is a better way to do it without using if/else
if(IsSynchronized)
{
lock(SyncRoot)
{
MyPrivateMethodToDoSomething();
}
}
else
{
MyPrivateMethodToDoSomething();
}
}
}
You can read more about writing thread safe collections on Jared Parson's blog

Locking critical section in object used across multiple threads

I've got a class that is instantiated within any number of threads that are spooled up as needed. This means that any number of instantiated versions of this class can be used at any one time, and there's a portion of this class that needs to be locked to prevent concurrent access.
To prevent data issues between the various threads, I needed a way to lock a section of code from the other instantiated versions of the class in other threads. Since there can be multiple instantiated versions of this class running around, I can't just use a private member variable to lock (and I know not to use the Type, or anything publicly accessible); so I used a private static member variable.
Is that a reasonable approach to this problem? Or is there a better solution?
Sample code below:
public class MyClass
{
private static object LockingVar = new object();
public void MyPublicMethod()
{
lock (LockingVar)
{
// Do some critical code
}
}
EDIT
MyPublicMethod is making calls to a local SQLExpress instance, it can perform selects in addition to updates and inserts, so it needs to finish before another thread gets in there and mucks it up.
Looks fine to me. I'd also mark the LockingVar as readonly.
Yes, with your sample code, you'll achieve a global critical section on the method for all instances of the class.
If that's what you're looking for (and you have to ask yourself if you really want to have only ever one thread running that method at a time), you can also use the [MethodImpl(MethodImplOptions.Synchronized)] which gets you basically the same feature.
[MethodImpl(MethodImplOptions.Synchronized)]
public static void MyPublicMethod()
{
// Do some critical code
}
Note: this amounts to write lock(this){} if it's a instance method or lock(typeof(MyClass)) if it's a class (static) method. Both are frown upon, so your lock(obj) pattern is better.
From MSDN:
Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.
http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx
Therefore your implementation seems to be right.

What are the gains of converting normal method to static?

As it is clear from question, if I convert a normal method to static what gains will I made?
You will gain clarity, because static makes it clear that the method doesn’t depend on an object state. You will also facilitate reusability because static methods may be used in more contexts (i.e. when you don’t have an instance of the class).
In general, it’s not really a question of gain, it’s a question of semantics: does your method depend on the object state? If so, make it non-static. In all other cases, make it static.
Apart from the semantic reasons mentioned above, static methods are generally faster (due to not having to create an object to call the method). They are subject to compile-time optimisations and as far as I recall, the CLR also performs some special optimisations on them.
Static function normally used for utility stuffs like ConverThisTypeToThatType(), and you can call them without having object of its class.
Ex: MessageBox.Show("Something");
here MessageBox is a Class and Show is static method in it, so we dont need to create object of MessageBox to call Show.

Should C# methods that *can* be static be static? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Should C# methods that can be static be static?
We were discussing this today and I'm kind of on the fence. Imagine you have a long method that you refactor a few lines out of. The new method probably takes a few local variables from the parent method and returns a value. This means it could be static.
The question is: should it be static? It's not static by design or choice, simply by its nature in that it doesn't reference any instance values.
It depends.
There are really 2 types of static methods:
Methods that are static because they CAN be
Methods that are static because they HAVE to be
In a small to medium size code base you can really treat the two methods interchangeably.
If you have a method that is in the first category (can-be-static), and you need to change it to access class state, it's relatively straight forward to figure out if it's possible to turn the static method into a instance method.
In a large code base, however, the sheer number of call sites might make searching to see if it's possible to convert a static method to a non static one too costly. Many times people will see the number of calls, and say "ok... I better not change this method, but instead create a new one that does what I need".
That can result in either:
A lot of code duplication
An explosion in the number of method arguments
Both of those things are bad.
So, my advice would be that if you have a code base over 200K LOC, that I would only make methods static if they are must-be-static methods.
The refactoring from non-static to static is relatively easy (just add a keyword), so if you want to make a can-be-static into an actual static later (when you need it's functionality outside of an instance) then you can. However, the inverse refactoring, turning a can-be-static into a instance method is MUCH more expensive.
With large code bases it's better to error on the side of ease of extension, rather than on the side of idealogical purity.
So, for big projects don't make things static unless you need them to be. For small projects, just do what ever you like best.
I would not make it a public static member of that class. The reason is that making it public static is saying something about the class' type: not only that "this type knows how to do this behavior", but also "it is the responsibility of this type to perform this behavior." And odds are the behavior no longer has any real relationship with the larger type.
That doesn't mean I wouldn't make it static at all, though. Ask yourself this: could the new method logically belong elsewhere? If you can answer "yes" to that, you probably do want to make it static (and move it as well). Even if that's not true, you could still make it static. Just don't mark it public.
As a matter of convenience, you could at least mark it internal. This typically avoids needing to move the method if you don't have easy access to a more appropriate type, but still leaves it accessible where needed in a way that it won't show up as part of the public interface to users of your class.
Not necessarily.
Moving public methods from static to non-static is a breaking change, and would require changes to all of your callers or consumers. If a method seems like an instance method, but happens to not use any instance members, I would suggest making it an instance method as a measure of future-proofing.
Yes. The reason "it can be static" is that it does not operate on the state of the object upon which it is called. Therefore it is not an instance method, but a class method. If it can do what it needs to do without ever accessing the data for the instance, then it should be static.
Yes, it should. There are various metrics of coupling that measure how your class depends on other things, like other classes, methods, etc. Making methods static is a way to keep the degree of coupling down, since you can be sure a static method does not reference any members.
I think it would make it a bit more readable if you marked it as static...Then someone who comes along would know that it doesn't reference any instance variables without having to read the entire function...
Personally, I'm a great fan of statelessness. Does your method need access to the state of the class? If the answer is no (and it is probably no, otherwise you wouldn't consider making it a static method), then yeah, go for it.
No access to state is less headache. Just as it is a good idea to hide private members that are not needed by other classes, it is a good idea to hide the state from members that don't need it. Reduced access can mean less bugs. Also, it makes threading easier as it is much easier to keep static members thread-safe. There is also a performance consideration as the runtime does not need to pass a reference to this as a parameter for static methods.
Of course the downside is that if you ever find that your previously static method will have to access the state for some reason, then you have to change it. Now I understand that this can be a problem for public APIs so if this is a public method in a public class, then perhaps you should think about the implications of this a bit. Still, I've never faced a situtation in the real world where this actually caused a problem, but maybe I'm just lucky.
So yeah, go for it, by all means.
Static methods are faster than the non-static ones so yes, they should be static if they can and there is no special reason for leaving them nonstatic.
I am surprised that so few are mentioning encapsulation here in fact. An instance method will automatically have access to all private (instance) fields, properties and methods. In addition to all protected ones inherited from base classes.
When you write code you should write it so that you expose as little as possible and also so that you have access to as little as possible.
So yes, it might be important to make your code fast which would happen if you're making your methods static, but usually more important then that is to make your code as incapable of creating bugs as possible too. One way to achieve that is to have your code have access to as little as possible of "private stuff".
This might seem irrelevant at first glance since the OP is obviously talking about refactoring which can not go wrong in this scenario and create any new bugs, however this refactored code must be maintained in the future and modified which makes your code have a bigger "attack surface" in regards to new bugs if it has access to private instance members. So in general I think the conclusion here is that "yes mostly your methods should be static" unless there are any other reasons for not having them static. And this simply because it's "better use of encapsulation and data hiding and creates 'safer' code"...
Making something static just because you can is not a good idea. Static methods should be static due to their design, not due to happenstance.
Like Michael said, changing this later will break code that's using it.
With that said, it sounds like you are creating a private utility function for the class that is, in fact, static by design.
If you were able to refactor a few lines out and the resulting method could be static, it is probably an indication that the lines you pulled out of that method don't belong in the containing class at all, and you should consider moving them into their own class.
It depends but generally I do not make those methods static. Code is always changing and perhaps someday I will want to make that function virtual and override it in a subclass. Or perhaps some day it will need to reference instance variables. It will be harder to make those changes if every call site has to be changed.
Personally I would have no choice but to make it static. Resharper issues a warning in this case and our PM has a rule "No warnings from the Resharper".
Inherently static methods that are for some reason made non-static are simply annoying. To wit:
I call my bank and ask for my balance.
They ask for my account number. Fair enough. Instance method.
I call my bank and ask for their mailing address.
They ask for my account number. WTF? Fail—should have been static method.
I suggest that the best way to think about it is this: If you need a class method that needs to be called when no instances of the class are instantioated, or maintains some kind of global state, then static is a good idea. But in general, I suggest you should prefer making members non-static.
You should think about your methods and classes:
How are you going to use them?
Do you need a lot of acces to them from different levels of your code?
Is this a method/class I can use in almost every thinkable project.
If the last two are 'yes', then your method/class should probably be static.
The most used example is probably the Math class. Every major OO language has it and all the methods are static. Because you need to be able to use them anywhere, anytime, without making an instance.
Another good example is the Reverse() method in C#.This is a static method in the Array class. It reverses the order of your array.
Code:
public static void Reverse(Array array)
It doesn't even return anything, your array is reversed, because all arrays are instances of the Array class.
As long as you make the new method private static it is not a breaking change. In fact, FxCop includes this guidance as one of its rules (http://msdn.microsoft.com/en-us/library/ms245046(VS.80).aspx), with the following information:
After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.
That being said, the first comment from David Kean more succinctly summarizes the concerns by saying this is actually more about being correct than about the performance gain:
Although this rule is classified as a performance issue, the performance improvement of making a method static is only around 1%.
Rather, it is more a correctness issue that could indicate an either an incomplete or a bug in the member by its failure to use other instance members. Marking a method static (Shared in Visual Basic) makes it clear on its intention not to touch instance state.
I would definitely turn anything I can into static for a different reason:
Static functions, when JIT'd, are called without a "this" parameter.
That means, for example, that a 3 parameter non-static function (member method)
gets pushed with 4 params on the stack.
The same function compiled as a static function would get called with 3 parameters.
This can free up registers for the JIT and conserve stack space...
I'm in the "only make private methods static" camp. Making a public method can introduce coupling that you don't want and may decrease testability: You can't stub a public static method.
If you want to unit test a method that uses a public static method, you end up testing the static method as well, which might not be what you want.
I look at it generally from a functional perspective of pure functions. Does it need to be an instance method? If not, you may benefit from forcing the user to pass in the variables and not mangling the current instance's state. (Well, you could still mangle state, but the point is to, by design, not do so.) I generally design instance methods as public members and do my best to make private members static. If necessary (you can then more easily extract them into other classes later.
In those cases, i tend to move the method to a static or utils library, so i don't be mixing the concept of the "object" with the concept of "class"

Categories

Resources