A static field in a generic class will have a separate value for each combination of generic parameters. It can therefore be used as a Dictionary<Type, whatever>
Is this better or worse than a static Dictionary<Type, whatever>?
In other words, which of these implementations is more efficient?
public static class MethodGen<TParam> {
public static readonly Action<TParam> Method = CreateMethod();
static Action<TParam> CreateMethod() { /*...*/ }
}
Or,
public static class MethodGen {
static readonly Dictionary<Type, Delegate> methods
= new Dictionary<Type, Delegate>();
public static Action<T> GetMethod<T>() {
//In production code, this would ReaderWriterLock
Delegate method;
if(!methods.TryGetValue(typeof(T), out method)
methods.Add(typeof(t), method = CreateMethod<T>());
return method;
}
static Action<T> CreateMethod<T>() { /*...*/ }
}
In particular, how does the CLR lookup the static fields by generic type parameter?
I like using generic types this way. In particular, I often have private nested generic classes for precisely this purpose.
The main thing I like about it is that it's hard not to get the initialization right this way (in terms of thread safety), given the way type initialization works. The only problem is what to do if initialization fails - occasionally I've resorted to remembering an exception to throw on first necessary access, but that's pretty rare.
I wouldn't like to guess at exactly how the CLR looks up the type via the type arguments, but I'm pretty sure it'll be optimised to heck and back :)
I believe that the generic (first) version would do the dictionary lookup at compile time, and therefore perform better at runtime.
However, it might use more memory.
I haven't profiled it (which is the only way to really answer this question - the difference in performance may be so small as to be meaningless) but I would hazard a guess that the locking is the expensive part. The CLR does do the locking for you - and does so in a way defined by experts in this field! - so I expect if there is a difference, it would be in favour of using the language feature rather than building it yourself with Dictionary + locking.
It doesn't store values for each generic type parameter as much as it really creates (conceptually anyways) N distinct classes - one for each type T that you use it with.
Related
I have a generic method that takes a request and provides a response.
public Tres DoSomething<Tres, Treq>(Tres response, Treq request)
{/*stuff*/}
But I don't always want a response for my request, and I don't always want to feed request data to get a response. I also don't want to have to copy and paste methods in their entirety to make minor changes. What I want, is to be able to do this:
public Tre DoSomething<Tres>(Tres response)
{
return DoSomething<Tres, void>(response, null);
}
Is this feasible in some manner? It seems that specifically using void doesn't work, but I'm hoping to find something analogous.
You cannot use void, but you can use object: it is a little inconvenience because your would-be-void functions need to return null, but if it unifies your code, it should be a small price to pay.
This inability to use void as a return type is at least partially responsible for a split between the Func<...> and Action<...> families of generic delegates: had it been possible to return void, all Action<X,Y,Z> would become simply Func<X,Y,Z,void>. Unfortunately, this is not possible.
No, unfortunately not. If void were a "real" type (like unit in F#, for example) life would be a lot simpler in many ways. In particular, we wouldn't need both the Func<T> and Action<T> families - there'd just be Func<void> instead of Action, Func<T, void> instead of Action<T> etc.
It would also make async simpler - there'd be no need for the non-generic Task type at all - we'd just have Task<void>.
Unfortunately, that's not the way the C# or .NET type systems work...
Here is what you can do. As #JohnSkeet said there is no unit type in C#, so make it yourself!
public sealed class ThankYou {
private ThankYou() { }
private readonly static ThankYou bye = new ThankYou();
public static ThankYou Bye { get { return bye; } }
}
Now you can always use Func<..., ThankYou> instead of Action<...>
public ThankYou MethodWithNoResult() {
/* do things */
return ThankYou.Bye;
}
Or use something already made by the Rx team: http://msdn.microsoft.com/en-us/library/system.reactive.unit%28v=VS.103%29.aspx
You could simply use Object as others have suggested. Or Int32 which I have seen some use. Using Int32 introduces a "dummy" number (use 0), but at least you can't put any big and exotic object into an Int32 reference (structs are sealed).
You could also write you own "void" type:
public sealed class MyVoid
{
MyVoid()
{
throw new InvalidOperationException("Don't instantiate MyVoid.");
}
}
MyVoid references are allowed (it's not a static class) but can only be null. The instance constructor is private (and if someone tries to call this private constructor through reflection, an exception will be thrown at them).
Since value tuples were introduced (2017, .NET 4.7), it is maybe natural to use the struct ValueTuple (the 0-tuple, the non-generic variant) instead of such a MyVoid. Its instance has a ToString() that returns "()", so it looks like a zero-tuple. As of the current version of C#, you cannot use the tokens () in code to get an instance. You can use default(ValueTuple) or just default (when the type can be inferred from the context) instead.
I like the idea by Aleksey Bykov above, but it could be simplified a bit
public sealed class Nothing {
public static Nothing AtAll { get { return null; } }
}
As I see no apparent reason why Nothing.AtAll could not just give null
The same idea (or the one by Jeppe Stig Nielsen) is also great for usage with typed classes.
E.g. if the type is only used to describe the arguments to a procedure/function passed as an argument to some method, and it itself does not take any arguments.
(You will still need to either make a dummy wrapper or to allow an optional "Nothing". But IMHO the class usage looks nice with myClass<Nothing> )
void myProcWithNoArguments(Nothing Dummy){
myProcWithNoArguments(){
}
or
void myProcWithNoArguments(Nothing Dummy=null){
...
}
void, though a type, is only valid as a return type of a method.
There is no way around this limitation of void.
What I currently do is create custom sealed types with private constructor. This is better than throwing exceptions in the c-tor because you don't have to get until runtime to figure out the situation is incorrect. It is subtly better than returning a static instance because you don't have to allocate even once. It is subtly better than returning static null because it is less verbose on the call side. The only thing the caller can do is give null.
public sealed class Void {
private Void() { }
}
public sealed class None {
private None() { }
}
I have a class with a static method which can operate on collections of objects of a couple of different types and act appropriately on them:
static void DoSomething(ICollection<TypeA> things)
{
// Do something with TypeA elements
}
static void DoSomething(ICollection<TypeB> things)
{
// Do something with TypeB elements
}
Elsewhere in my code there are a lot of dictionaries which use either TypeA or TypeB for their keys, and a variety of types for their values. I end up with a number of calls to DoSomething(dictionary.Keys), which I think would be better served by methods which accept dictionary and pass on the .Keys collection to the appropriate overload.
It seems I can do this if I strongly type the dictionary:
static void DoSomething(IDictionary<TypeA,object> dictionary)
{
DoSomething(dictionary.Keys);
}
but then I need an overload for every IDictionary<TypeA,TValues> which it might encounter, even though the method doesn't need to know what TValues is to work.
I alternatively seem to be able to accept a generic IDictionary, but then have to recast Keys to an appropriate type:
static void DoSomething(IDictionary dictionary)
{
DoSomething((ICollection<TypeA>) dictionary.Keys);
}
This doesn't seem wise since calls using dictionaries with unsupported key types won't upset the compiler and I would presumably have to rely on Reflection to choose the correct overload.
Am I missing a better option?
You could create a generic method that accepts a type parameter for the type of the dictionary values:
static void DoSomething<TVALUE>(IDictionary<TypeA, TVALUE> dictionary)
{
DoSomething(dictionary.Keys);
}
The best thing to do (if you have control over TypeA and TypeB) is to make both types implement an interface like this:
interface IDoSomething
{
void DoSomething();
}
...and change the dictionary to be a Dictionary<IDoSomething, T>.
Then you can simply iterate through the dictionary keys and call DoSomething() on each one.
Other solutions tend to violate the Open/Closed Principle. For example, if you do as Markus suggested then somewhere you'll wind up with a switch/series of if-statements like this:
if (key is TypeA)
DoSomething<TypeA>(key);
else if (key is TypeB)
DoSomething<TypeB>(key);
else
throw new Exception();
This is a code smell and indicates violation of this principle. For example, what happens when you need to put a key of type TypeC into the dictionary? You have to remember to change the place where this code is (thus this code is not closed for modification). And if you forget then it's a runtime error instead of a compilation error. And the problem only gets worse as your code expands, because these switch/if-statements start popping up all over the place.
If you're unable to make TypeA and TypeB implement the same interface then perhaps there's another way to refactor toward SOLID principles. If you have any questions about something else in the context of this problem, I'm sure the SO community will be happy to answer a separate question.
I'm writing a library in C# that I will later use for an application, and I want the library to be as efficient as sanely possible (ie. don't over-complicate things too much to make it more efficient). However, I have this question about how to most efficiently use reflection on a class/methods and to illustrate the question I've simplified my class a lot down to this:
class MyClass
{
private static Dictionary<string, object> methods;
public void Method1()
{
// Do something.
}
public void Method2()
{
// Do something else.
}
}
Now, what I want is from within the class (a private method yet to be created), take a string containing the method-name, then fire the method, simple as that. The easiest way of doing this would be to just look at the name, get a method with that name, and execute it, but that forces me to use reflection a lot of times. This private method can potentially be called thousands or tens of thousands of times, and it need to be quick. So I came up with two possible solutions. As you can probably see I've added a static dictionary containing string->object (replacing object with actual type, just wrote object cause that works with both my examples). Then I'd add a static constructor that goes trough the class and adds all the methodinfos to the methods-dictionary. And then comes the question, on creation of a new instance of the class, should I create bound delegates to the methods and put those in a non-static private dict, or should I simply fire the methods using the MethodInfo in the methods-dictionary?
The average use-case will create 10 instances of this class, and have 1000+ calls to the method that should fire either Method1 or Method2 depending on it's string-argument (and no, switch-case is not an option because of the extensibility of the class, as said, this was a simplified version). What would be the most efficient way of achieving this?
Obviously no one can answer the question without actually trying it and doing performance tests to see if your goal is met or not.
Reflection is a lot faster in modern versions of the framework than it used to be, but it still is not as fast as simply invoking a delegate.
My suggestion would be to start with your proposed solution: build the cache of method infos once:
class MyClass
{
static Dictionary<string, MethodInfo> cache = new ...
public void InvokeByName(string name)
{
MethodInfo methodInfo = GetMethodInfoFromCache(name);
methodInfo.Invoke(this, new object[] {});
}
When asked to invoke a method identified by a string on a particular instance as the receiver, look up the method info by name and then invoke it with the given receiver. Measure the performance of that and see if it meets your goal. If it does, great; don't waste any more of your valuable time trying to make something faster that is already fast enough.
If that is not fast enough then here's what I'd do:
class MyClass
{
static Dictionary<string, Action<MyClass>> cache = new ...
public void InvokeByName(string name)
{
GetActionFromCache(name).Invoke(this);
}
So what does GetActionFromCache do? If there is already an action in the cache, we're done. If there is not, then obtain the MethodInfo via Reflection. Then use the Expression Tree library to build up a Lambda:
var methodInfo = SomehowGetTheMethodInfo(name);
// We're going to build the lambda (MyType p)=>p.<named method here>()
var p = Expression.Parameter(typeof(MyType), "p"));
var call = Expression.Call(p, methodInfo);
var lambda = Expression.Lambda<Action<MyType>>(call, p);
var action = lambda.Compile();
And now you have an action in hand that you can invoke with the instance. Stick that thing in the cache.
This is, incidentally, at an incredibly simplified level, how "dynamic" works in C# 4. Our problem is enormously complicated by the fact that we have to deal with the receiver and arguments being of any type. You have it very easy comparatively.
Since you will obtain all of the MethodInfo instances and the name to map them to (presumably through the MethodInfo.Name property, you can go one step further and create a compiled lambda expression in the form of a delegate which you can execute.
First, it's assumed that all of your methods will have the same signature. In this case, it's an Action<T> delegate. With that, your dictionary will look like this:
// No need to have the dictionary **not** readonly
private static readonly IDictionary<string, Action<MyClass>> methods =
new Dictionary<string, Action<MyClass>>;
Then, in your static constructor, you would use reflection to get all of the MethodInfo instances:
static MyClass()
{
// Cycle through all the public instance methods.
// Should filter down to make sure signatures match.
foreach (MethodInfo methodInfo in typeof(MyClass).
GetMethods(BindingFlags.Public | BindingFlags.Instance))
{
// Create the parameter expression.
ParameterExpression parameter = Expression.
Parameter(typeof(MyClass), "mc");
// Call the method.
MethodCallExpression body = Expression.Call(pe, methodInfo);
// Compile into a lambda.
Action<MyClass> action = Expression.Lambda<Action<MyClass>>(
body, parameter).Compile();
// Add to the dictionary.
methods.Add(methodInfo.Name, action);
}
}
Then, your private method would look like this:
private void ExecuteMethod(string method)
{
// Add error handling.
methods[method]();
}
The benefit here is that you get the performance of compiled code, while paying a very small price (IMO) in code complexity (in creating the delegate). Granted, there is a slight overhead in calling the code through a delegate, but that's been vastly improved (it had to be with the introduction of LINQ, since they would be executed many, many times).
If I had the choice here, I would probably go with Henk's suggestion and use dynamic. Method invocations are blazingly fast (much faster than ordinary reflection and almost like normal method calls).
You may also find inspiration by looking at this class, which extends DynamicObject and illustrates how you could do the dynamic invocation of methods.
However, if you wish to support 3.5 or keep your options open and you have no objections to using a 3rd party library, then this can still be fairly easily accomplished:
void Invoke( string methodName )
{
this.CallMethod( methodName );
}
CallMethod creates a DynamicMethod delegate for invoking that particular method and caches it in case you call the same method again. There are also extensions for invoking methods with parameters and a ton of other useful reflection helpers.
If you prefer to cache the delegate yourself (we use a ConcurrentDictionary and WeakReferences to do this, which means it might get garbage collected), just call DelegateForCallMethod instead.
The library supports both 3.5 and 4.0. WP7 does not support Reflection.Emit and therefore cannot use IL generation and DynamicMethod. However, WP 7.5 does support this (but Fasterflect, as the library is called, does not yet support it).
From your comment:
Well, simply put it's connected to a server, the server sends commands in the form of <name> <param1> <param2> ... <paramN>, and the name determines what functionality should be performed. I want to be able to just add functions with matching names (or rather, I've created an attribute that lets me name methods other than their method-name cause command-names might be numeric), cause the list of names is looooong, and I don't want to do a switch-case.
You can solve this problem with a simple command interface and a table-driven factory for a matching instance (or a type, if the command instances are not reusable).
public interface ICommand {
void Execute();
}
public class Processor {
private static Dictionary<string, ICommand> commands;
static Processor() {
// create and populate the table
}
public void ExecuteCommand(string name) {
// some validation...
commands[name].Execute();
}
}
No reflection involved.
To create a new command, just create a new class that implements ICommand and add the corresponding line to the commands table inside the Processor static constructor.
public class FooCommand : ICommand {
public void Execute() {
// foo away!
}
}
...
public class Processor {
static Processor() {
...
commands["foo"] = new FooCommand();
...
}
}
There are many advantages to this design, aside from performace. Your commands are isolated from each other, changes to one command or the creation of new commands won't impact other commands. They're better testable and easier to maintain. Even the processor can be closed (in an OCP way) if you can maintain your table in a config file or a database, for example.
You can certainly find alternative designs and ways to pass parameters to the commands, but I hope this gives you the basic idea.
In this particular case you can declare your dictionary slightly differently and get the result you are after::
class MyClass
{
private static Dictionary<string, Action<MyClass>> methods;
public void Method1()
{
// Do something.
}
public void Method2()
{
// Do something else.
}
static MyClass(){
methods = new Dictionary<string, Action<MyClass>>();
foreach(var method in typeof(MyClass).GetMethods(
BindingFlags.Public | BindingFlags.Instance)
)
{
methods.Add(
method.Name,
Delegate.CreateDelegate(typeof(Action<MyClass>),method)
as Action<MyClass>);
}
}
}
This code has the advantage of not using code generation. However if you have methods of different signatures then a different approach will be needed. Here we are creating open instance delegates. (Note this doesn't always work correctly if MyClass is a struct or if any of these methods are generic virtual methods).
The fastest way of doing something is not to do it at all. Have you considerer just making interface like:
interface ICallMe
{
void CallByName(string name, object args);
}
This way if some of the implemetations wants to be insanely smart it can do reflection+caching+IL generation, the others can simply use if/switch.
Downside - significantly less fun to implement and debug.
Invoking a MethodInfo is slow. So I think creating a new dictionary for each instance should be good enough. Another option is to create a delegate that accepts the instance (Action<MyClass>) using Expressions (and then store them in the static dictionary):
MethodInfo method = typeof(MyClass).GetMethod("Method1");
var parameter = Expression.Parameter(typeof(MyClass));
var call = Expression.Call(parameter, method);
var lambda = Expression.Lambda<Action<MyClass>>(call, parameter);
Action<MyClass> del = lambda.Compile();
Have you considered using Code Generation and T4 Text Templates?
http://msdn.microsoft.com/en-us/library/bb126445.aspx
http://msdn.microsoft.com/en-us/library/bb126478.aspx
Then you could use a case statement.
Something like
partial Class MyClass
{
public void Exec(string funcToExec)
{
swtich(funcToExec)
{
<#
foreach(MethodInfo mi in
typeof(MyClass).GetMethods(BindingFlags.Public | BindingFlags.Static)
{
if(mi.Name != "Exec"){
#>
case : "<#= mi.Name #>"
<#= mi.Name #>();
<#
}}
#>
}
}
}
I want to do something like this:
public static TResult MyCast<TSource, TResult>(TSource item)
{
return (TResult)item;
}
Without restrictions on TSource or TResult and avoiding unnecessary boxing if possible.
Edit: I want to stress out, that I want a simple casting of types, not elaborate type conversion here. It would be perfectly ok to fail at casting, say string to int.
Is there any sane way to do this using CLR 2.0?
Edit: this is a simplified version, so it's pretty useless, yes.
But consider casting generic collections, such as this:
public static Dictionary<string, TResult> CastValues<TSource, TResult>(this Dictionary<string, TSource> dictionary)
After some discussions with my co-workers, it seems like there's no simple way to implement such a feature (if at all possible), so I'm stuck with code bloat of several very simple methods for different situations (i.e. up- and downcast of reference types and casting of some value types) :(
Too bad I can't use .NET 4.0 with all it's dynamic et al goodness.
How would
x = MyCast<SourceType, ResultType>(y)
be any more useful than
x = (ResultType)y ?
This is straightforward when TSource and TResult are both reference types.
If one or the other are value types, how do you want it to work? Value types can't inherit from each other, so it's not a matter of doing an up- or down-cast. You might expect numeric conversions between, say, int and double, but you'd have to code these yourself: .NET doesn't treat them as typecasts. And conversion between, say, DateTime and string involves more intelligence (what format? which culture? etc.).
If you're just handling reference types then this method can be a one-liner. If you want to handle value types as well then you'll need to write special case code for the various combinations.
Edit: Convert.ChangeType does a reasonable job at encapsulating the various conversions between value types. However you mentioned you're keen not to introduce boxing: Convert.ChangeType isn't generic and it takes an object.
I think that the problem you are trying to solve is the same as the problem that you cannot cast a collection of one type to a collection of another type.
eg
class Obj1
{}
class Obj2:Obj1
{}
List<Obj2> srcList = GetList();
List<Obj1> castedList=(List<Obj2>) srcList;//this line wont compile
I have not done much at actually looking at the CLR code
However on the asuumption that it is like C++ what you would have here is actually different values stored in the collection. In other words srcList would contain a list of pointers to object 2's interface in castedList you would have a pointer to the the interface of the object 1's within object 2.
In order to resolve this you would need to have your casting function iterate through each of the items within the collection. However in order to be able to iterate through the items the list would have to implement some sort of enumeration interface. So the enumeration interface would need to be a constraint on the casting function.
So the answer would therefore be no.
However if you were prepared to implement this with restrictions on the in types you could have:
static class ListCast<TSource,TResult,TItemType>
where TSource:IEnumerable<TItemType>
where TResult:IList<TItemType>,new()
{
static TResult Cast(TSource list)
{
TResult castedList=newTResult();
foreach(TtemType item in list)
{
castedList.Add(TItemType)item);
}
return castedList;
}
}
you can just do this:
public static TResult MyCast<TSource, TResult>(TSource item)
{
return (TResult)((object)item);
}
Would love to hear how this could be bad.
The question is in the title, why :
return double.IsNaN(0.6d) && double.IsNaN(x);
Instead of
return (0.6d).IsNaN && x.IsNaN;
I ask because when implementing custom structs that have a special value with the same meaning as NaN I tend to prefer the second.
Additionally the performance of the property is normally better as it avoid copying the struct on the stack to call the IsNaN static method (And as my property isn't virtual there is no risk of auto-boxing). Granted it isn't really an issue for built-in types as the JIT could optimize this easilly.
My best guess for now is that as you can't have both the property and the static method with the same name in the double class they favored the java-inspired syntax. (In fact you could have both as one define a get_IsNaN property getter and the other an IsNaN static method but it will be confusing in any .Net language supporting the property syntax)
Static Methods are thread safe, methods on primitives generally need to be thread safe to support threading in the platform (meaning at least safe from internal race conditions), instance methods take a managed pointer to a structure, meaning that the structure/primitive might be modified concurrently while the method executes, on the other hand static methods take a copy of the structure/primitive and therefore are safe from threading race conditions.
If the structure is intended to be thread safe, then the methods should be made instance methods only if they do atomic operations, else static methods should be chosen.
(As another option, instance methods that use locking could be used but they are more expensive than, copying)
Edit: #VirtualBlackFox I've prepared and example to show that instance methods on structures are not thread safe even on immutable structures:
using System;
using System.Threading;
namespace CA64213434234
{
class Program
{
static void Main(string[] args)
{
ManualResetEvent ev = new ManualResetEvent(false);
Foo bar = new Foo(0);
Action a = () => bar.Display(ev);
IAsyncResult ar = a.BeginInvoke(null, null);
ev.WaitOne();
bar = new Foo(5);
ar.AsyncWaitHandle.WaitOne();
}
}
public struct Foo
{
private readonly int val;
public Foo(int value)
{
val = value;
}
public void Display(ManualResetEvent ev)
{
Console.WriteLine(val);
ev.Set();
Thread.Sleep(2000);
Console.WriteLine(val);
}
}
}
The display Instance method prints:
0
5
even though the structure is immutable. For thread safe methods use static methods.
Interesting question; don't know the answer - but if it really bugs you, you could declare an extension method, but it would still use the stack etc.
static bool IsNaN(this double value)
{
return double.IsNaN(value);
}
static void Main()
{
double x = 123.4;
bool isNan = x.IsNaN();
}
It would be nicer (for the syntax) if C# had extension properties, but the above is about the closest you can get at the moment, but it should "inline" quite well anyway.
Update; thinking about it, there is another difference between static and instance; C# always calls instance methods with "callvirt" rather than "call", even if ther type is sealed an non-nullable. So perhaps there is a performance benefit from having it static? Luckily, extension methods still count as static, so you get to retain this behavior.
#Pop Catalin: I'm not ok with what you said in :
If the structure is intended to be thread safe, then the methods should be made instance methods only if they do atomic operations, else static methods should be chosen.
Here is a small program that demonstrate that static methods don't solve this problem for structs :
using System;
using System.Threading;
using System.Diagnostics;
namespace ThreadTest
{
class Program
{
struct SmallMatrix
{
double m_a, m_b, m_c, m_d;
public SmallMatrix(double x)
{
m_a = x;
m_b = x;
m_c = x;
m_d = x;
}
public static bool SameValueEverywhere(SmallMatrix m)
{
return (m.m_a == m.m_b)
&& (m.m_a == m.m_c)
&& (m.m_a == m.m_d);
}
}
static SmallMatrix s_smallMatrix;
static void Watcher()
{
while (true)
Debug.Assert(SmallMatrix.SameValueEverywhere(s_smallMatrix));
}
static void Main(string[] args)
{
(new Thread(Watcher)).Start();
while (true)
{
s_smallMatrix = new SmallMatrix(0);
s_smallMatrix = new SmallMatrix(1);
}
}
}
}
Note that this behavior can't be observed with double values on common processor as most x86 instructions have a version working with 64bits chunks such as movl.
So thread safety doesn't seem a good reason for IsNaN to be static :
The framework should be platform agnostic and so it shouldn't presuppose things like the processor architecture. IsNaN thread-safety is dependent on the fact that 64bits values are always accessed and modified atomicaly on the target architecture (And Compact framework targets aren't x86...).
IsNaN is useless by itself and in a context where multiple thread could access someVar this code is anyway unsafe (regardless of the thread safety of IsNaN) :
print("code sample");
if (!double.IsNaN(someVar))
Console.WriteLine(someVar);
What i mean is that even if IsNaN is implemented by doing == comparisons with all possible NaN values... (not really possible)
...who care that the value evolve during the execution of the method if anyway it could have changed once the method terminate... or it could even be an intermediate value that should never have been here if the target architecture isn't x86...
Accessing intristic values in two different threads is NOT safe in general so i see no interest in providing some illusion of safety by putting any method static when dealing with structs or any other type,
The distinction between an instance and a static is a fundamental point which the C# language (and Java as you say) chooses to make clear (in C++, you can call a static method through an instance, but thats just syntax - under the hood instance.StaticX is the same saying instance Class.StaticX.
The move towards fluent interfaces has started unravelling a lot of this though...
I remember the words of a mentor, praying that any method, that does not use any other variables than the parameters are static methods.
I really do not know why, and havent thought on the behind, but logically, it seems good.
Interested in the answer anyhow ;-)
I think Marc was onto the answer.
The problem is when you need to call instance methods on valuetypes, the value is boxed. This would cause a severe performance penalty.
Double.IsNan follows the same pattern as String.IsNullorEmpty. The latter behaves as it does because there is regrettably no way to declare that a non-virtual instance method should be usable with a null "this". While such behavior might be odd for mutable reference types, it would be very useful for things that have to be reference types but which should behave semantically like immutable values. For example, the "String" type would have been much more convenient if invoking its properties on a null object would have behaved identically to invoking them on an empty string. As it is, there's an odd mish-mosh of contexts in which a null string object will be regarded as an empty string, and those in which trying to use one will generate an error. It would have been much cleaner if string had behaved consistently as a value type which is initialized to an empty string.