c#


C# static method from object


I have various objects of different types.
For all of them, I want to call a static method of their class. All the classes share the same method.
How can I call this static method without explicitly calling the class?
You could accomplish this by putting a method in each object that calls the corresponding static method. However, the fact that you want to do this suggests that your design might be able to be improved. If you'd tell us what you're trying to accomplish, someone may be able to suggest a better approach.
If these classes all extend the same base class, then calling the method on the base class will work.
For example:
public class Base
{
public static DoSomething()
{
//something
}
}
public class A: Base
{
}
public class B: Base
{
}
The following method calls execute the same code:
A.DoSomething();
B.DoSomething();
Base.DoSomething();
You want to call every method on each of the individual classes? You have to call them explicitly, referencing each class individually.
Does the static method for every class have the same common code? Put it into a static class for use by all of the other classes, or create one or more extension methods.
Are you looking for something like you have something like List<object> where all of the objects are guaranteed to have a static method named, say MethodX() ?
If so you could reflect on them, look for the method name, and execute that.
Either that or inheritance like the others mention (which would be the correct way to go).
If you need to have a specific implementation for each type, I don't think a static method is the right approach... Instead, you shoud define an interface implemented by all your classes. You can then call the instance method defined by the interface on each object :
public interface IDoSomething
{
void DoSomething();
}
public class A: IDoSomething
{
public void DoSomething()
{
// implementation for A
}
}
public class B: IDoSomething
{
public void DoSomething()
{
// implementation for B
}
}
Of course, if you don't need a specific implementation for each type, then you can just call Base.DoSomething (as explained by David)
I'm not sure what exactly you're trying to do. But using my imagination I come up with this implementation.
internal class Program
{
private static void Main(string[] args)
{
var staticMethodClasses = new List<StaticMethodClassBase>
{new ClassA(), new ClassB()};
foreach (StaticMethodClassBase item in staticMethodClasses)
{
Type t = item.GetType();
MethodInfo staticMethod =
t.GetMethod("DoSomething", BindingFlags.Static | BindingFlags.Public);
staticMethod.Invoke(null, null);
}
}
}
public abstract class StaticMethodClassBase
{
}
public class ClassA : StaticMethodClassBase
{
public static void DoSomething()
{
Console.WriteLine("Class A");
}
}
public class ClassB : StaticMethodClassBase
{
public static void DoSomething()
{
Console.WriteLine("Class B");
}
}

Related Links

add a glyphicon-user to a TextBoxFor control in MVC ASP.NET
what is the explanation of output of C# statement
Advice on managing DLLs [closed]
Robocopy in c# not copying data
How to Update The Value of Selected Rows to a Access Database In C#
Importing Pyro in IronPython ScriptEngine
Linq query to check substring between a list and string
String builder returning the same values
Show resx translation key names on page
C# Linq XML InvalidOperationException
Why does System.Net.Http not get packaged? [duplicate]
Azure Service Bus Topic subscribe from CRM plugin
Method and field in parent or base class [closed]
Mesh Decimation (averaged face value?) + triangulation | .NET/C# library
Enable button only if two ListViews have at least 1 item (via WPF Triggers)
Convert custom DateTime string to DateTime object [duplicate]

Categories

HOME
spring-boot
locale
display
assign
artifactory
terminal
foreach
sequence
zabbix
scapy
osx-yosemite
phpexcel
coding-style
minimax
olap
apache-httpclient-4.x
decoding
hql
infopath
luis
css-float
vala
opengraph
handle
poisson
rollupjs
tftp
typeclass
uibarbuttonitem
sqldependency
emr
recreate
schedule
akamai
opencsv
wordpress-rest-api
snapkit
rtos
machine-code
javax
geocomplete
cocoa-scripting
rythm
realloc
lex
office-interop
server-side-swift
uitextview
geminabox
flask-socketio
serialversionuid
visio-2010
hellosign
grib
overhead
catalyst
cedar-bdd
konakart
particle-system
recurring
boost-bind
mod
skbio
datamodel
nslocalizedstring
videoview
javapackager
openhab
textblob
azure-mobile-app
sparkcore
p4python
web-standards
vspackage
jeet-grid
aiff
uiblureffect
qf-test
atg-dynamo
xpand
isl
cs193p
rssi
farpoint-spread
google-mirror-api
dylan
azure-pack
exi
junction-table
gwt2
simplemembership
vline
dnsbl
derived-class
states
google-email-audit-api
sup
nsscrollview
motorola-droid
mcpd
session-hijacking
nbehave
norton
s60
conditional-operator
activescaffold
browser-state
web-search
zend-acl

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App