Static/Non static classes and methods - c#

Lets assume i got this class:
public class Utlities
{
int Age;
public static void DoSomething()
{
Age ++;
}
}
My questions to this:
Does anyone from outside - can access DoSomething() in same time? - assuming YES
If answer on 1. is YES then if couple classes executing this method the value will be changing without any problems?
Class is non static but method is static so is the method only accessible one time in specific time?
What in case i have couple instance of that class if other classes will access specific instance of class Utilities true is that DoSomething method will be shared/the same across all instances of class Utilites or for each instance of Utilities class other outside classes will be accessing different DoSomethingmethods?
Lets take another example:
public class Utlities
{
static int Age; // <------------------------------------
public static void DoSomething()
{
Age ++;
}
}
How it will be in this case?
And last:
public static class Utlities //<-------------static now
{
static static int Age;
public static void DoSomething()
{
Age ++;
}
}
As class is static now all inside have to be static - does it mean that only one outside class can access it in same time?
Last questions as i want to create some help class which inside i would have common methods that could be useful in my program should i use static class with static methods or non static class with static methods - please of explanation here as well.

Declaring a variable/class/method as static wont change the accessability.
As an example, a static method belongs to the class itself, meanwhile a nonstatic method belongs to each object of that class.
If you have a static variable
static int ageCounter;
all objects of the class, holding this variable, will see the same ageCounter
In addition to that, your question was about multiple calls of that static method by different classes. If this happens in a single thread you wont have problems at all. Trouble starts if different threads try to work on the same data.

Apart from the fact that your first example will not compile (can't access instance field from a static method), static doesn't restrict use of that method. It is entirely possible that multiple thread access that method at the same time.
Instead static means that you can access that method (or field) without an instance of that Utlities class.
You can just use
Utlities.DoSomething();
instead of (which doesn't even compile)
var myutls = new Utlities();
myutls.DoSomething(); // <-- compile error: cannot be accessed with an instance reference
In the static class example, you can't even do a new Utlities(). The compiler will not accept it (Cannot create an instance of the static class).
Be careful with a static value like that static int Age: this means that your application can store just one Age value (which isn't always what you want)

(Presuming that your Age field was meant to be static, too.)
Declaring a variable/class/method as static wont change the accessability.
As an example, a static method belongs to the class itself, meanwhile a nonstatic method belongs to each object of that class.
In addition to that, your question was about multiple calls of that static method by different classes. If this happens in a single thread you wont have problems at all. Trouble starts if different threads try to work on the same data.
Last, you mentioned the missing static modifier on the class. That modifier is only there to prevent a class from being instantiated and can be used if (and only if) all members of the class are static, too.

Related

C# Put Static Class Inside Dictionary

I was unclear in an earlier question I ask so I will try to be more explicit.
Is there a way to put a static class inside of a dictionary so that its functions can be called? If this is not possible, what is the best alternative that doesn't involve using instances that you can suggest?
Here is how I would like to use it:
static class MyStatic : IInterface
{
static void Do(){}
}
static class MyStatic2 : IInterface
{
static void Do(){}
}
class StaticMap
{
static Dictionary<Type,IInterface.class> dictionary = new Dictionary<Type,IInterface.class>
{
{Type.1, MyStatic}
{Type.2, MyStatic2}
};
}
// Client Code
class ClientCode
{
void Start()
{
StaticMap.dictionary[Type.1].Do();
}
}
There are some fundamental reasons why you can't do that directly:
Static method calls are bound at compile-time
Static calls are not inherited - they are tied to the class that defines them
There is no implicit base type (and therefore no polymorphism) between static methods, even if the name, inputs, and outputs are all the same
Since your signature is the same for every static method, you could store a Action in the dictionary instead:
static Dictionary<Type,Action> dictionary = new Dictionary<Type,Action>
{
{Type.1, MyStatic.Do}
{Type.2, MyStatic2.Do}
};
then you can call the Action directly:
void Start()
{
StaticMap.dictionary[Type.1]();
}
It's slightly repetetive because you have to specify the method name in the dictionary as well, but it's type safe.
A key question is whether you want to call a single method on each type or whether you need to call multiple methods belonging to each type.
If it's just a single method, then what D Stanley suggested is the answer. If you store a number of Actions, each representing a method with the same signature on a different static class, then you're accomplishing what you said.
However that raises a question - why the constraint that each method must belong to a separate static class? This approach would work just as well if some or all of the methods belonged to the same class.
If you need to call more than one method from each class then an Action no longer works. You'd have to store collections of Action, which a) means class instances, and b) is a lot more complicated than just using interfaces and class instances.
One way to manage instances is by using a dependency injection container to create class instances for you. Using that approach, you can create non-static classes without having to go through the hassle of explicitly making them singletons. But you can tell the container to only produce one of each and reuse it. For example, using Castle Windsor:
container.Register(Component.For<ISomeInterface,SomeClass>));
Now every time the container is asked to provide an instance of ISomeInterface it will always provide the same instance of SomeClass.
Because the dependency you're looking for varies by type (Dictionary<Type, Something>) it sounds like what you're looking for might be related to generics. But it would be necessary to take a step back from the smaller problem and understand a slightly larger picture of what you're trying to accomplish.
Instead of having the entire class as static, create a Singleton instance.
public class Foo
{
public static Foo _Foo;
public Foo()
{
_Foo = this;
}
}
Then you may add it to your list, and also inherit from Interfaces, etc.

Is there any reason to not use the static modifier in C#?

I am pretty new to C# programming, and I am still learning. I was wondering if there is any particular reason to not use the static modifier when creating a method, for me it just seem much simpler. I tried looking at MSDN but that isn't much help if I don't know what half the words mean.
For example this:
using System;
namespace StaticModifier
{
class Program
{
static void Main(string[] args)
{
SayHi();
}
static void SayHi()
{
Console.WriteLine("Hi");
}
}
}
Seems much simpler than this:
using System;
namespace StaticModifier
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.SayHi();
}
void SayHi()
{
Console.WriteLine("Hi");
}
}
}
So would anyone be willing to explain? Keep in mind that I am pretty new so please keep it simple :)
A non-static method of the class Program provides the current instance of the class Program..
Since Program doesn't contain any variables or properties that are used, you don't need to molest your CPU with unnecessary objects.
And Program p = new Program(); is not the way you would instantiate your "Program". The Main() method is static and is usually contained within a static class with static methods. You can't call dynamic methods from a static method, since there is no instance of the object.
TL;DR
If you want to pass this (the current object) to the method and your method utilizes its properties, then don't use static. Otherwise there is absolutely no reason not to use static!
You wouldn't use the static modifier if you had a class that would require more than 1 instance of itself. For example if you have a class named car that included the static keyword you would only ever be access the members of that class via the static reference of that class. So you could never have 2 instances of a car object.
Which depending on what your program is trying to do maybe appropriate. However you may look to use the static keyword if you had a class names player score. As this would only ever exist once, and unless you have more that one player you would want 1 instance of the player score. Which means you could either consider a singleton instance or just have a static class.
There are many many reasons why you either would or wouldn't make use of the static modifier. However to some up when you should use it is impossible and depends on the specific scenario of the application you are creating.

Why the compiler allow to create an object of non static class in static context?

As per the definition
Non static things can not be accesses in static context
then how does it allow to create an object of non-static class to the static main method.
class Test
{
static void Main()
{
Base x = new Derived();
x.Foo();
}
}
This is not the right definition. Here is one from MSDN:
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.
Note that you are not accessing nont-static members of Test, and neither you are using some outer variables.
Compare this, which is not allowed, to your snippet:
class Test
{
int t = 1;
static void Main()
{
Base x = new Derived();
x.Foo(t); // not allowed!
}
}
You understand that completely wrong. Static methods can't access the instance members, because they don't have the this reference. That isn't a prohibition, simply a fact of a missing reference. If you supply the reference (eg. through method parameter, creating an instance inside etc.), there's nothing to stop you from doing the call.
In other words,
class Test
{
int testField = 23;
static int GetTestField()
{
// Doesn't compile - static methods don't have a
// `this` reference to get the instance member
return testField;
}
}
Fails to compile. However,
public class Test
{
public int testField = 23;
}
public static class Tester
{
public static int GetTestField(Test test)
{
return test.testField;
}
}
works just fine, because you pass the instance of Test you're trying to access.
You're not forbidden from using instance members in static methods (that would make them almost useless!). You just don't have a this reference, as simple as that.
Not really for Stack Overflow, but okay:
To understand this, it's helpful to know something of what's going under the hood. Basically, the CPU doesn't really have a notion of things like "classes" or "methods". That's why higher level programming languages invented calling conventions - common ways to invoke methods and pass them parameters. So, for example, if you wanted to call Print(23);, it might do something like this:
push 23
call Print
The Print method would then know it's parameter is store on top of the stack, and it could retrieve it using the current stack pointer, for example.
When classes came around, they brought a concept known as encapsulation. Basically, the class effectively has its own memory storage, and its own methods. When you want to access that data (or functionality), you have to do it through the class instance. On the lower level, this is usually handled by passing the reference to the object as the first parameter of the method. So, calling test.GetTestField(23, 21) (where test is a reference to an instance of the Test class) would do something like this:
push test
push 23
push 21
call Test.GetTestField
(this is all pseudo-code, the actual way the compiler handles that differs between calling conventions and languages; for example, parameters are often sent in reverse-order)
This way, the GetTestField method has access to the instance of the Test class (which it may or may not need for what it does). So when the method has to get the value of an instance field, for example, it can get this.testField (in C# and most other languages, the this can be ommited and is implied - everytime you access an instance field/method/etc. inside a class, it adds the this under the covers).
Static methods don't have this luxury - but that's also why they exist in the first place. They're used for functionality that is related to the class in which they are defined, but they don't require the instance members of the class (or they get the instance reference some other way).
Example - there's an int class in .NET framework (actually, it's a struct, but let's ignore that for now). The class has a couple of static methods, and a couple of instance methods. For example, the instance method ToString() takes the value of the int, and converts it to a string value - for this, it (obviously) needs to have the value of the integer. On the other hand, it has a static method Parse(string), which takes a string parameter with the string value of the integer, and converts it to an integer. It creates a new integer, and parses the string value into it as an integer value. Since it creates a new instance of integer, it doesn't actually use this, and as such, can be safely declared as static. This avoids some extra costs of instance methods (even more so in languages where methods are virtual by default), at the very least, passing the extra parameter, but more importantly, it broadcasts the intent of the method - "I don't read or modify the instance members of this class". If you didn't have static methods, and you wanted to write the Parse method mentioned above, you'd have to create an instance of int first and call Parse on that.
you need to remember that you are not accessing the Foo() directly but with the help of instance variable x.That is always possible.
Note : you can not access non static members as below:
void Foo()
{
}
static void Main()
{
Foo();//compile error
}
You absolutely can access non-static members in a static context, as long as you have a valid reference to an object.
The only reason a static context is different from a non-static context in this regard, is that the static context doesn't have the this reference (which is implied when you access non-static members without explicitly referencing an object). The non-static context, on the other hand, always has an implicit this reference.
The problem isn't that you can't access non-static fields/methods/etc in a static context, it's that you can't access non-static fields/methods without an instance.
In the code you provided, there is an instance of Base, and so you can access it's methods, regardless of the context.
You can make object of non-static class in static method but could not access the non-static member int that class. Suppose you have an object of Derived class as a member of Test then you wont be able to access that object in static method main.
Define a non-static method in Test class and try to call it from Main method you will get error again.
class Test
{
Derived d = new Derived();
static void Main()
{
// You can not access d here.
// You can not access MyFun() here.
}
void MyFun()
{
}
}

C# - Class , constructors and Resharper - clarification

I use Resharper tool in visual studio
Consider a very simple class written below.
class Test()
{
//constructors do not have any return type.
Test()
{
System.Console.WriteLine("Hello World!");
}
static Test()
{
System.Console.WriteLine("Hello World in Static constructors");
}
public void A()
{
System.Console.WriteLine("A simple function in a class");
}
}
class Program
{
static void Main(string[] args)
{
var asa = new Test(); //Implicitly Typed local variables.
asa.A();
}
}
Using var (the compiler has to infer the type of the variable from the expression on
the right side of the initialization statement).
I have some clarification questions and they are below.
Extra burden to compiler?
How many constructors a class can have?
Why is static constructor called first ? (I checked out by putting a breakpoint?)
Why not Test asa = new Test(); is not preferred by Resharper?
Is it really a good idea to use Resharper first as a beginner? (Myself being a newbie to C and .net programming!)
Thanks in Advance.
Any extra burden to the compiler is basically irrelevant - it should not be part of your decision about whether or not to use var. As noted in comments, it may well require slightly more work for the compiler when you use explicitly declared variable... but again, it's not going to be significant.
A class can have any number of constructors... although it will become unwieldy pretty quickly.
The static constructor will be called once, before the first use of the class (whether that's via a static method or a constructor call). Read the C# spec for more details - section 10.12 of the C# 5 spec includes:
The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
An instance of the class type is created.
Any of the static members of the class type are referenced.
You can configure ReSharper to suggest alternatives, or treat them as warnings, etc. Make it work however you think it should, on this front.
Negligible if any. The return type would otherwise be compile checked. You shouldn't base decisions on it, anyhow.
As many as you want as long as they are distinguishable.
Static constructors are part of the type definition. They are invoked when the type is first referenced.
What message are you receiving? R# is configurable.
Edit:
(You can't beat the Skeet).
yes, there is some extra work required, but it is possible to use var keyword only in those situations in which it is pretty easy for the compiler to infer the type.
There is no constraint on number of constructors, but there are some rules constructors have to follow (ie: it needs to be clear for the compiler which constructor to call)
I can't telly you why - let's say this is just one of the rules. The interesting thing is beforefieldinit (http://stackoverflow.com/questions/610818/what-does-beforefieldinit-flag-do, http://csharpindepth.com/Articles/General/Beforefieldinit.aspx)
I personally think that in this case it is just a matter of taste. Some people tend to use var as much as they can, while others do the opposite. I try to use when:
I am working with collections (or it takes a lot of text to tell the compiler about the type: instead of:
Dictionary<<OneOfMyClasses, OtherClasss> dictionary = new Dictionary<OneOfMyClasses, OtherClass>();
I tend to use var:
var dictionary = new Dictionary<OneOfMyClasses, OtherClass>();
Please mind that it doesn't affect readability of the code (i.e. it is still easy to understand what is actually happening).
Thanks Everyone. After some time spent on research, I would like to add some points that might help someone.
Disclaimer:(The following points were derived(or even pasted) from codeproject and other such websites.
1) Every single class can have only one static constructor.
Reason: Static constructor must be parameter-less or simply, constructor overloading is not permitted. And since CLR is going to call this constructor, we do not have any control over passing values to this function. As we directly can’t call static constructors, there is no point in having multiple static constructors.
class Test
{
static Test() {...}
static Test(int a) {...} //would throw error as "Static constructor must be parameter less"
}
2) Static constructor should be declared without any access specifier.
Reason: Again CLR is going to call the static constructor not any object of the class. Hence, we donot need any access-specifier.
3) Static constructor must operate only on static variables of that class
Reason: Non-static members are specific to the object instance. There is no point in modifying a variable whose value depend/bind to their specific object instance.
4) Why should I use a static constructor ? Give me one good example
Reason: You can use a static constructor, say when you want to log the operations that you are going to perform using that class. MSDN says "A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file".
5) When exactly a static constructor is called ?
Answer: The user has no control on when the static constructor is executed in the program.
.As others and MSDN points out "A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced."
6)When using base class and derived class in C#, when a new instance of a derived class is created, does base class constructor is called first or derived class constructor is called first?
Answer: The base class constructor is called first and then the derived class constructor.
Code example
class DerivedClass : ParentClass
{
public DerivedClass()
{
Console.WriteLine("Derived class constructor!");
}
}
class ParentClass
{
public ParentClass()
{
System.Console.WriteLine("Parent class constructor!");
}
}
class Program
{
static void Main(string[] args)
{
var a = new DerivedClass(); //Implicitly Typed local variables.
}
}
7) Why in your above examples, both constructors have public access specifier ? What if I specify private or do-not specify access specifier at all?
Answer: When you do not specify access specifier(this case, the constructor automatically becomes private) or whenever you use a private access specifier, the class cannot be instantiated. Whenever a class contain one or more private constructors it strictly (!) cannot be instantiated. This type of constructors are called special instance constructor and is generally used when all the members of a class are static methods. (Probably the Math class should be a good example.)
**8)Bonus question on inheritance. Does a class inherit from two different classes ?
Strictly No. C# supports only direct inheritance and ofcourse you can use interfaces.For example,
interface Test
{
void abc();
}
class DerivedClass : ParentClass, Test //Test should not be a class. It can be a interface.
{
public DerivedClass()
{
Console.WriteLine("Derived class constructor!");
}
public void abc()
{
//should be publicly defined!
//non public method could not implement from interface Test
}
}
class ParentClass
{
public ParentClass()
{
System.Console.WriteLine("Parent class constructor!");
}
}

C# Instance Constructor vs Static Constructor

What are the differences between the two? I've only used one kind of constructor and I believe it's the static constructor. Only familiar with C++ and Java.
Static constructor is called the first time your class is referenced i.e.
MyClass.SomeStaticMethod()
Instance constructor is called every time you do 'MyClass dummy = new MyClass()' i.e. create instance of the class
Semantically first is used when you want to ensure that some static state is initialized before it is accessed, the other is used to initialize instance members.
Static constructors allow you to initialize static variables in a class, or do other things needed to do in a class after it's first referenced in your code. They are called only once each time your program runs.
Static constructors are declared with this syntax, and can't be overloaded or have any parameters because they run when your class is referenced by its name:
static MyClass()
{
}
Instance constructors are the ones that are called whenever you create new objects (instances of classes). They're also the ones you normally use in Java and most other object-oriented languages.
You use these to give your new objects their initial state. These can be overloaded, and can take parameters:
public MyClass(int someNumber) : this(someNumber, 0) {}
public MyClass(int someNumber, int someOtherNumber)
{
this.someNumber = someNumber;
this.someOtherNumber = someOtherNumber;
}
Calling code:
MyClass myObject = new MyClass(100, 5);
The static constructor runs only once for all instances or uses of the class. It will run the first time you use the class. Normal constructors run when you instantiate an object of the class.
Everything you should need to know about static constructors can be found here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors

Categories