What would be the purpose of having a static method? [duplicate] - c#

This question already has answers here:
Should C# methods that *can* be static be static? [closed]
(21 answers)
Closed 2 years ago.
While not positive, I'm pretty sure the static keyword makes methods and fields belong to a class and not an instance of a class. For fields, this makes sense to me, as static fields become global variables essentially. For methods though, I don't understand why it would be advantageous or hurtful to make a static method.
For example, what would be the difference between:
class RandomClass {
public static void Method() {
Console.WriteLine("Hello World");
}
}
class Program {
static void Main(string[] args) {
RandomClass.Method();
}
}
and
class RandomClass {
public void Method() {
Console.WriteLine("Hello World");
}
}
class Program {
static void Main(string[] args) {
RandomClass randomObject = new RandomClass();
randomObject.Method();
}
}

A static method in C# is a method that keeps only one copy of the method at the Type level, not the object level. That means, all instances of the class share the same copy of the method and its data. The last updated value of the method is shared among all objects of that Type.
Reference: https://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/static-methods-in-C-Sharp/#:~:text=A%20static%20method%20in%20C%23,all%20objects%20of%20that%20Type.

Related

Does a static method in a non-static class make it a static class c# [duplicate]

This question already has answers here:
What is a "static" class?
(11 answers)
Closed 2 years ago.
Possibly a stupid question but I need to ask it anyway for my own context. I have a non-static class that has a static method and a non-static method. What happens to the class, is it now a static class and a non-static class, meaning there is a static version of the class with just the static method in memory and when you instantiate the class there will be an instance with all the non-static methods? I may be confusing myself. C# .net framework.
Non-static class with static and non-static method.
public class Class1
{
public static string Class1Method()
{
return "static";
}
public void Class1Method2()
{
//Not Static
}
}
Second class that would be using it.
public class Class2
{
public void Class2Method()
{
Class1.Class1Method();
new Class1().Class1Method2();
}
}
Class1 is considered non-static.
However, if you were to run say ReSharper over Class1 as it appears above, it may suggest to you to consider making it static because Class1 has no instance members. i.e. static class Class1 as well as public static void Class1Method2.
Otherwise, as it stands now, there is no point to making Class1Method2 an instance method because there are no instance members to act upon.

Should Program class be static? [duplicate]

This question already has answers here:
Instantiating the class that contains static void Main()
(8 answers)
c# : console application - static methods
(5 answers)
Closed 1 year ago.
I am getting the following Warning in Visual Studio 2019, after creating a new ASP.NET Core 3 project:
Warning CA1052
Type 'Program' is a static holder type but is neither static nor NotInheritable
public class Program
{
public static void Main(string[] args)
{
// ...
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
// ...
}
vs
public static class Program
{
public static void Main(string[] args)
{
// ...
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
// ...
}
Should I add the static modifier? Why / Why not? Pro's and Cons'?
Edit: This is a ASP.NET Core 3 API
In more basic terms the message could be imagined to say:
Your class 'Program' only seems to contain methods that are declared as static and as a result it can not participate in an inheritance hierarchy. Declare it as static (or sealed if you're targeting an ancient version of .net that doesn't support static classes) to more accurately reflect what its design sentiment is
It's a recommendation, to mark your class as static because it only contains static stuff. This will prevent anyone making the mistake of trying to inherit from it and thinking they can then do something useful inheritance-wise with the inherited version
Microsoft don't mark it as static for you because there's nothing special about Program per se; you could put non static methods in it, or your could put your static void Main in another class, like Person, that IS instantiable.
class Person{
public string Name {get;set;}
static void Main(){
Person p = new Person();
p.Name = Console.ReadLine();
}
}
This would work fine; a class does not have to be static to host the application entry point and in this case the class couldn't be static because it has non static members. It can be (and is, in the main) instantiated in the main. It's not called Program; there isn't a class called Program anywhere and this tiny app will still run (doesn't do much..)
In your case, either do as recommended and add a static modifier to your class, because it will make your program that bit more robustly engineered, or add an instance member if you can think of a valid reason for instantiating Program, or ignore the message and carry on with your non static class that contains only static methods - it'll still work

Accessing public methods in same class requires an Instance?

I'm a newbie to C# so forgive this question but I'm confused: Why do I need an instance of class Program to access method Sandbox which is public and in the same class?
namespace GoogleTest
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.Sandbox();
}
public void Sandbox()
{
...
}
}
}
public void Sandbox()
{
...
}
is the important part: This method is not marked static, so it is not callable on the class, but on instances of the class. If you want to be able to call it directly, you need
public static void Sandbox()
{
...
}
and can't use this.
Because you're trying to access it from within a static method, but Sandbox is an instance method.
If you make Sandbox static, this won't be required:
static void Main(string[] args)
{
Sandbox();
}
public static void Sandbox()
{
...
}
Note that it also doesn't have to be public - public allows it to be used by other classes and within other assemblies, but within Program, that's not required.
Static methods exist at the Class level, you can consider them Global functions. Any non static methods are instance level and just as the name implies you can only execute instance methods on an instance. So by instantiating the class you have created an instance and now can call any public method. In your example you could also call any private methods or constructors because you are creating the instance from with the class you are creating.

What is the main difference between static class & Singleton class [duplicate]

This question already has answers here:
Difference between static class and singleton pattern?
(41 answers)
Closed 8 years ago.
here is two piece of class code one is for Singleton and other one is for static class. i like to understand in programming when one should use static class and when one should use Singleton class?
both are used to hold the global object as a result we can access those data from any where of the program when it is running. scope is broad for both....the life time of application.
1) i really do not find any article which can guide me when i should use static class and when Singleton class should be good choice. i have seen people manage db connection using Singleton class.
2) what is the main difference between Singleton class & static class ?
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
public static class TestStatic //: ITestSingleton
{
public static void doAction(string args)
{
Console.WriteLine("Test Static :: " + args);
}
}
Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.
Use singleton when you need a class that has only one instance, and you need to provide a global point of access to the instance
A singleton is basiccly an entry point to a single instance of a class. The instance of that class can be passed to another method as a reference.
A static class doesn't have this behaviour (only static methods are allowed).

Is a static member variable common for all C# generic instantiations?

In C# I have a generic class:
public class MyGeneric<ParameterClass> where ParameterClass: MyGenericParameterClass, new() {
public static int Variable;
}
Now in C++ if I instantiated a templated class with different parameters each complete class would get it's own Variable, so I just can't say
MyGeneric.Variable = 1; // invalid in C++
in C++, but seems like I can do so in C#.
I'd like to clarify...
If I have a generic with a static member variable is that variable shared among all generic instantiations?
Section 25.1.4 of the ECMA C# Language specification
A static variable in a generic class declaration is shared amongst
all instances of the same closed constructed type (ยง26.5.2), but is
not shared amongst instances of different closed constructed types.
These rules apply regardless of whether the type of the static
variable involves any type parameters or not.
You may see this blog post: Static fields in generic classes by Gus Perez
You can't do that in C# as well.
MyGeneric.Variable = 1;
Consider the following example from ECMA Language Specification.
class C<V>
{
static int count = 0;
public C()
{
count++;
}
public static int Count
{
get { return count; }
}
}
class Application
{
static void Main()
{
C<int> x1 = new C<int>();
Console.WriteLine(C<int>.Count); // Prints 1
C<double> x2 = new C<double>();
Console.WriteLine(C<double>.Count); // Prints 1
Console.WriteLine(C<int>.Count); // Prints 1
C<int> x3 = new C<int>();
Console.WriteLine(C<int>.Count); // Prints 2
}
}
MyGeneric<MyClass>.Variable
MyGeneric<MyOther>.Variable
These two are different static variables treated like separate classes.
No, it is not. Generic types can be "open" or "closed." An open type is one like List<T> where the type parameter isn't defined; List<int> is a closed type.
Essentially, the open type isn't treated as a proper "Type" by the runtime - only the closed versions are true types. So, MyGeneric<int> and MyGeneric<string> are two entirely different types, and thus have their own instances of the static variable.
This is made more obvious by the fact that you can't call your static member in the way you suggest: MyGeneric.Variable will not compile in C#.
This console application code illustrates it quite simply:
class Program
{
static void Main(string[] args)
{
Test<int>.i = 2;
Test<string>.i = 8;
Console.WriteLine(Test<int>.i); // would write "8" if the fields were shared
Console.WriteLine(Test<string>.i);
// Console.WriteLine(Test.i); // does not compile
// Console.WriteLine(Test<>.i); // does not compile
}
}
class Test<T>
{
public static int i;
}
No, it is not shared.
Each MyGeneric<T> class will resolve to a different runtime type, for each possibility of T.
Please check that there is no non-generic MyGeneric class with the Variable static member.
As stated, the answer to your question is no. However, what you can do is use a parent class to your generic class, and have your static variable in there. Any method you need to call could be abstracted into that parent class.
abstract class MyBase
{
protected static MyBase selected;
public abstract void Deselect();
}
class MyGeneric<T> : MyBase
{
public void Select()
{
if (selected != null)
{
if (selected != this)
{
selected.Deselect();
}
}
selected = this;
//...
}
public override void Deselect()
{
//...
}
}

Categories

Resources