Consider the following classes
class A
{
public static int i;
}
class B
{
public static A a{get;}=new A(); // without new A(), B.A will be null
}
now,
B.a gives a new instance of A and since the variable "i" of class A is static, I can not access "i" through B.a i.e B.a.i is compile time error.
I understand that if I do like below,
class B
{
static class A
{
static int i;
}
}
then I could do B.A.i.
So my question is how could I access static members of a static member of a class? Is it possible at all and is there any other pattern that I can use.
Also note that making class "A" as static and having class "B" as
class B
{
public static A a{get;}
}
gives a compile time error that "static type cannot be used as return type".
Since i is static member of A you can access it directly like
class B
{
public static A a {get;} = new A();
public int ii{get;} = A.i;
}
how could I access static members of a static member of a class?
If something is a member of a class -- static or not static -- that means it's either a value or a reference to an instance of something. Therefore, if you know you have an instance of a class but that class has static members itself, then just access those members statically:
class MyClass
{
public static string Value { get; }
}
string x = MyClass.Value;
You don't need to instantiate a class to access it's static members.
Simply you can try :
int value = A.i;
If you need, you can add a static class too :
public static class A
{
public static int i;
}
and you can use anywhere in your code like :
int value = A.i;
Related
Static members can't be called with instance, like instance.myStaticProperty.
Is there any way, that I can have an instance variable that will be an alias of static self class? like:
class myClass
{
public string a ="hello";
public static string b ="world";
public myClass myVariable = global::myClass; // <--- phseudo code
}
and i could call:
myClass instance= new myClass();
instance.myVariable.b; //
No, there is not. The closest you get is using a using.
Your static class definition:
class ClassA
{
public static string A = "A";
}
And to use it:
using StaticClassA = ConsoleApp1.ClassA;
class Program
{
static void Main(string[] args)
{
string a = StaticClassA.A;
}
}
Not too much to gain though, but it might ease your naming a little.
Another (somewhat cooler) option is a static using:
using static ConsoleApp1.StaticClassA;
class Program
{
static void Main(string[] args)
{
string a = A;
}
}
You're attempting to do an anti-pattern there.
Static properties are properties not defined in an instance (object) of that class, but by the class itself. And as such, you can access and modify them whenever you choose to, provided you have the required scopes to do so.
I don't see the problem in calling MyClass.StaticProperty = <some expression>, if indeed the functions the static property do, are static. If it's something part of the object, something you don't connect with the class itself, i.e it might be different for each instanced object of that class, then just turn it into a regular property instead.
Example of some static properties and methods:
public class DoMath
{
public static string Pi { get; private set; } = "3.14";
public static double X {get; set;}
public static double Y {get; set;}
public static double Sum() => X + Y;
}
DoMath.X = 3.5;
DoMath.Y = 4;
double result = DoMath.Sum();
Console.WriteLine($"Pi is equal to {DoMath.Pi}.");
If you truly wish something to be static, then don't try to make it non-static. Simply declare it as such.
Static members are shared across all instances of the class or all instances of Class Of T of same T.
So you can access static properties outside of class by using the ClassName.VarName or directly by the VarName from within the class.
You can access static fields and properties and methods from all non static methods.
You can also add an instance member mapping a static member.
Instances of a static thing can't exist in addition to the static existence itself.
So you can write this:
class myClass
{
public string a = "hello";
static public string b = "world";
public string B { get { return b; } set { b = value; } }
public void DoSomething()
{
b = "new world";
}
}
And use it like that:
myClass instance= new myClass();
instance.DoSomething();
myClass.b = "another world";
instance.B = "C# world";
We know that If a class is made static, all the members inside the class have to be static; there cannot be any instance members inside a static class. If we try to do that, we get a compile time error.
But if have an instance member inside a static method, I do not get a compile time error.
public static class MyStaticClass
{
// cannot do this
//int i;
// can do this though.
static void MyStaticMethod()
{
int j;
}
}
Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
public class MyStaticClass
{
static int j; //static member
int i;//instance member
static void MyStaticMethod()
{
i = 0; // you can't access that
j = 0; // you can access
}
}
Its not instance member, its (j) a local variable inside a static method.
Consider following non-static class.
public class MyStaticClass
{
int i; //instance member
static void MyStaticMethod()
{
i = 0; // you can't access that
}
}
The above class has a instance member i, you can't access that in a static method.
static void MyStaticMethod()
{
int j;
}
You have a local variable (j) inside your static method.
For your information from MSDN:
You can define a class as static if you want to guarantee that it
can't be instantiated, can't derive from or serve as the base for
another type, and can contain only static members.
Static members are initialized before the static member is accessed
for the first time and before the static constructor, if there is one,
is called.
What's the difference between static classes, and static methods? I want to learn the differences, and when I might use one vs. the other.
For example, I have a class like this:
static class ABC
{
public int a;
public void function_a()
{
a = 10;
}
}
and another class like this:
class DEF
{
public static int a;
public static void function_a()
{
a= 10;
}
}
I have used the second type of class many times, and I know the usage. What's the usage of the first example?
Your first example will not compile, a static class must have all static members.
The difference between just using some static methods and a static class is that you are telling the compiler that the class cannot be instantiated. The second example you can create an object of the DEF class even though there are no instance methods in it. The ABC class cannot be instantiated with the new operator (will get a compile-time error).
When to Use Static Classes
Suppose you have a class CompanyInfo that contains the following methods to get information about the company name and address.
C#
class CompanyInfo
{
public string GetCompanyName() { return "CompanyName"; }
public string GetCompanyAddress() { return "CompanyAddress"; }
//...
}
These methods do not need to be attached to a specific instance of the class. Therefore, instead of creating unnecessary instances of this class, you can declare it as a static class, like this:
C#
static class CompanyInfo
{
public static string GetCompanyName() { return "CompanyName"; }
public static string GetCompanyAddress() { return "CompanyAddress"; }
//...
}
Use a static class as a unit of organization for methods not associated with particular objects. Also, a static class can make your implementation simpler and faster because you do not have to create an object in order to call its methods. It is useful to organize the methods inside the class in a meaningful way, such as the methods of the Math class in the System namespace.
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();
}
}