how to call static method inside non static method in c# ?
Interviewer gave me scenario :
class class1
{
public static void method1(){}
public void method2()
{
//call method1()
}
How can we do it
A normal practice is to call static method with class name.
See: Static Classes and Static Class Members (C# Programming Guide)
The static member is always accessed by the class name, not the
instance name. Only one copy of a static member exists, regardless of
how many instances of the class are created.
So your call would be like:
class1.method1();
But it is not necessary
You can call the static method without class name like:
method1();
But you can only do that inside the class which holds that static method, you can't call static method without class name outside of that class.
class1.method1();
Same as you'd call any other static method
Apparently (as Selman22 pointed out) - the classname isn't necessary.
So
method1();
would work just as well
if you call the method in the some class you just call it like this
public void method2()
{
method1();
}
but if it should been called from another class you have to precede it with the name of the class
public void method2()
{
class1.method1();
}
You type the method name out, and then compile and run it:
class class1
{
public static void method1(){}
public void method2()
{
method1()
}
}
Related
Now I am working with c# code that looks something like this
public class MyClass
{
public static void Method1()
{
//Do something
}
public void Method2()
{
//Do something
Method1();
}
}
Now what if I replace the code as:
public class MyClass
{
public static void Method1()
{
//Do something
}
public void Method2()
{
//Do something
MyClass.Method1();
}
}
Now what is the difference in above 2 representations.
Is it the same or does it show some different working.
Any help is appreciated.
The second is just a longer version of the previous. If you are in the same class as the static method, you do not need to specify the class name, you can, but you don't need to (much like specifying this for instance methods).
Inside the class there is no difference but the difference comes when you try to invoke them from outside the class. For instance method you need a instance of your class whereas for static method that's not required. But inside your class you can just say
public class MyClass
{
public static void Method1()
{
//Do something
}
public void Method2()
{
Method1(); //you don't have to qualify it
}
}
My understanding of the method structures is limited to a very limited spectrum of structures:
public / private
static
void / variable returns
string, int etc.
So why can't I call a method within the same class?
class ClassName
{
public void Method1()
{
// do stuff...
}
public static void Method2()
{
// This won't work?
Method1();
// do stuff...
}
}
You can't call a non-static method from a static method.
If you really want to do that from withing a static method, you need to instantiate the class, something like:
class myClass
{
public void Method1(){
//Stuffs
}
public static void Method2(){
myClass c=new myClass();
c.Method1();
}
}
You can't call a method that isn't static from a static method..
Static = belongs to the class
Otherwise it belongs the instance of the class.
See MSDN reference for more information about static methods.
You can't call a non static element from a static context. You would have to create an instance of your class in your static method and call the non static method from that instance. A static method can be called without an instance.
Inside of a public class:
public static class LogReporting
I have the following method:
public void RunTimerJobs()
{
SPAdministrationWebApplication centralAdmin = SPAdministrationWebApplication.Local;
try
{
foreach (SPService service in centralAdmin.Farm.Services)
{
Guid traceGuid = new Guid("d3beda82-38f4-4bc7-874f-ad45cebc9b35");
Guid eventGuid = new Guid("3ea057b3-0391-4c33-ac8d-412aecdda97d");
var traceJob =
from jobDefinition in service.JobDefinitions
where jobDefinition.Id == traceGuid
select jobDefinition;
if (traceJob != null && traceJob.Count() == 1)
{
traceJob.First().RunNow();
}
var eventJob =
from jobDefinition in service.JobDefinitions
where jobDefinition.Id == eventGuid
select jobDefinition;
if (eventJob != null && eventJob.Count() == 1)
{
eventJob.First().RunNow();
}
}
}
catch (Exception ex)
{
//Loggers.SharePointLogger logger = new Loggers.SharePointLogger();
//logger.WriteTrace(ex.Message, LogProduct.MonitoringView, LogTraceSeverity.Unexpected);
}
However it will not allow me to compile citing that RunTimerJobs() "cannot declare instance members in a static class"
To my knowledge, none of the 'instance members' I declare are able to be labeled as static, so is there just a fundamental issue with the setup (i.e. a static class) or am I missing some little snippet?
Your class is static thus you cannot have any instance members because you will never instantiate the class.
To be able to use the RunTimerJobs() method you would need to create an instance of the LogReporting class, i.e.
LogReporting logReporting = new LogReporting();
logReporting.RunTimerJobs();
This obviously won't work though because your class is defined as static and you cannot create instances of it.
Either make your method static or remove the static keyword from your class declaration - depending on what you require.
I see no instance related logic in your method so it should be safe to mark it as static.
Remember
Classes can have a mixture of instance and static members as long as the class isn't marked static.
And
Only mark classes as static when you know that ALL members (properties, methods etc...) will be static as well.
The compiler's being pretty clear here. You're declaring a static class, and static classes can only contain static members. So this is okay:
public class NonStaticClass
{
public void InstanceMethod() {}
}
And this is okay:
public static class StaticClass
{
public static void StaticMethod() {}
}
But this isn't:
public static class StaticClass
{
public void InstanceMethod() {}
}
If you wanted to declare instance members, why did you declare LogReporting as a static class?
When class marked as static, then all it's members should be static (instances creation is not allowed). You can read more about static classes on msdn.
So, if you want to have instance (non-static) method, then remove static keyword from class definition:
public class LogReporting
{
public void RunTimerJobs()
{
//...
}
}
In this case you should create LogReporting instance to call your method:
LogReporting log = new LogReporting();
log.RunTimerJobs();
Another option for you - making your method static:
public static class LogReporting
{
public static void RunTimerJobs()
{
//...
}
}
In this case you don't need instance of LogReporting:
LogReporting.RunTimerJobs();
Did you try:
public static void RunTimerJobs()
For a static class, the members must also be static. If you are unable make the members static, then you must make the class non-static as well.
It's generally a good idea to use non-static classes if you can, as static classes increase the complexity of unit testing as they cannot be mocked out easily. Of course if you have a legitimate need to use a static class, then by all means do so.
I have couple of question regarding Static Constructor in C#.
What exactly are Static Constructor and how they are different from non-static Constructor.
How can we use them in our application ?
**Edited
public class Test
{
// Static constructor:
static Test()
{
Console.WriteLine("Static constructor invoked.");
}
public static void TestMethod()
{
Console.WriteLine("TestMethod invoked.");
}
}
class Sample
{
static void Main()
{
Test.TestMethod();
}
}
Output :
Static constructor invoked.
TestMethod invoked.
So, this means that static constructor will be called once. if we again call Test.TestMethod(); static constructor won't invoke.
Any pointer or suggestion would be appreciated
'
Thanks
Static constructors are constructors that are executed only ONCE when the class is loaded. Regular (non-static) constructors are executed every time an object is created.
Take a look at this example:
public class A
{
public static int aStaticVal;
public int aVal;
static A() {
aStaticVal = 50;
}
public A() {
aVal = aStaticVal++;
}
}
And consider this code:
A a1 = new A();
A a2 = new A();
A a3 = new A();
Here, static constructor will be called first and only once during the execution of the program. While regular constructor will be called three times (once for each object instantiation).
static constructors are usually used to do initialization of static fields for example, assigning an initial value to static fields.. Do keep in mind that you will only be able to access static members (methods, properties and fields) on static constructors.
If you need to "execute the static constructor multiple times", you can't do that. Instead, you can put the code you want to run "multiple times" in a static method and call it whenever you need. Something like:
public class A {
public static int a, b;
static A() {
A.ResetStaticVariables();
}
public static void ResetStaticVariables() {
a = b = 0;
}
}
You use them the same way you use instance constructors - to set default values. Only in this case you'll be initializing static fields, so static constructors get executed only once.
Be aware that the code in static constructor won't be executed until the first call to the class was made.
it runs when class is loaded.
It will print :
{
hi from static A
A
}
public class A{
static A{
print("hi from static A");
}
public A() {
print("A");
}
main() {
new A();
}
}
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");
}
}