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.
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
}
}
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()
}
}
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();
}
}
In Java I can write:
public class Foo {
public static Foo DEFAULT_FOO;
static {
DEFAULT_FOO = new Foo();
// initialize
DEFAULT_FOO.init();
}
public Foo() {
}
void init() {
// initialize
}
}
How can I get the same functionailty in C# (where static members are initialized before use)? And, if this is a bad thing to try to do, what is a better approach?
you use a static constructor, like this:
public class Foo
{
static Foo()
{
// inits
}
}
Here's more info.
Bottom line: it's a paramaterless constructor with the static keyword attached to it. Works just like the static block in Java.
Edit: One more thing to mention. If you just want to construct something statically, you can statically initialize a variable without the need for the static constructor. For example:
public class Foo
{
public static Bar StaticBar = new Bar();
}
Keep in mind that you'll need a static constructor if you want to call any methods on Bar during static initialization, so your example that calls Foo.Init() still needs a static constructor. I'm just sayin' you're not limited, is all. :)
Static is still the keyword in C#:
public class Foo {
public static Foo DefaultFoo;
static Foo {
DefaultFoo = new Foo();
// initialize
DefaultFoo.init();
}
public Foo() {
}
void init() {
// initialize
}
}