Calling a Static Method from an Object Instance in C#
The short answer: You can’t call a static method from an object instance in C#. It’s allowed in VB.NET, but in C# you must use reflection or delegates instead.
Of the two workarounds, delegates is the preferred option. Delegates perform faster, and you get compile-time errors rather than run-time errors.
But it’s Friday, and I’m feeling a bit lazy. Here’s the syntax for using reflection:
typeof(<type name>).GetMethod("<method name>").Invoke(null, new object[]{<list of parameters if any>});
If you want the long answer to why C# doesn’t allow static methods to be called from instances, you’ll need to read the posts and comments for parts one, two and three on Eric Lippert’s blog, Fabulous Adventures in Coding.
But maybe not on a Friday.
Related Posts
- Reflecting on reflection in .NET
- P/Invoke Hooray();
- WCF Instance Context
- Using WCF to return HTML
- Switch By Type in C#
Those blog links seem to mainly be about calling statics on generic parameters… (rather than just a standard object instance). Which is indeed annoying, but I’d also say, generally not necessary in a normal design; you’re probably better off using some sort of singleton instance or something.
You’re right Simon. (Did I mention I was being lazy?) The main insight I derived from reading all the articles and comments was that the “static” keyword meant more than I thought it did. In C#, “static” means that the compiler must know — at compile time — exactly which method to call. That rules out most polymorphic behavior. It also makes calling static methods from instances problematic. VB.Net doesn’t quibble here, but C# opts for compiler errors.
Thanks for this. very nice one.
can you also please provide a sample on using delegates to static methods using object.
Thanks, Dutt
short & good explanation, but seems it is controdicting the what says in below articles. just sharing the link incase uses feel useful.
Can static methods be called using object/instance in .NET
http://msdotnetsupport.blogspot.com/2009/12/static-methods-calling-using-object-c.html
Dutt, there’s a good example on using delegates to call static methods in C# on MSDN. Check out Microsoft’s delegates tutorial: http://msdn.microsoft.com/en-us/library/aa288459%28VS.71%29.aspx
Nayak, the article you linked to makes the same point I was making in my comment. Using Invoke() to call a static method won’t give you the expected polymorphic behavior. It will always call the static method on the base class.