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

C# 7 Local Functions: are attributes / aspects allowed?
Difference between OData complex and entity types
Specified argument was out of the range of valid values. oracle parameter
Convert File To Byte-Array, Save In Access-DB, Read From DB And Create File
C# ASP.NET 3.5: zip more than 65535 dynamic files with SharpZipLib
Find a row containing two values in foreach Excel interop
Is it safe to compare decimals casted from doubles
CS0234: The type or namespace name 'Description' does not exist in the namespace 'System.Web.Http' (are you missing an assembly reference?)
Referencing Public Viewcontroller.cs from another Class using Xamarin.IOS
App crashes on debbug mode but it works on release [on hold]
Stopping File system echoing/looping
How to access DisplayName annotation within loop rather than from Model in Razor View?
cannot implicitly convert type 'system.timespan' to double
Using Refit in ْXamarin the portal project
using Interop.outlook and ews
Returning Nested Objects on .NET API using OData

Categories

HOME
macros
gsm
fortran
process
azure-eventhub
glsl
hex
crm
opc-ua
symfony-3.2
country-codes
browserstack
apache-httpclient-4.x
urllib2
resharper
hdf5
github-flavored-markdown
box2d
background-image
spring-webflow
summernote
url-parameters
cherrypy
polybase
fastboot
concatenation
poisson
deployment-descriptor
expressionengine
stack-trace
angular2-changedetection
marionette
key-bindings
voyager
apache-falcon
device-driver
stencyl
motion
gem-fury
cowboy
mtm
binary-decision-diagram
rexx
firefox-developer-edition
django-cors-headers
encoder
spring-data-commons
rivets.js
standard-error
ear
dotnet-cli
photoshop-script
hellosign
toggleclass
joystick
x12
jigsaw
hoare-logic
falcon
gdi
kik
mrunit
redquerybuilder
cloud-storage
teamwork
genome
wingdb
attiny
douglas-peucker
iphone-6
fedena
clearcanvas
sync
object-oriented-database
xml-validation
aspnet-compiler
cab
dynamic-expresso
brew
webpage-screenshot
beep
erlide
mysql-connector
win-prolog
eeprom
cgaffinetransform
lgpl
dongle
pkcs#7
morfik
bootstrap-protocol
content-delivery-network

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