Is there any reason to not use the static modifier in C#? - 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.

Related

How do I utilize a single instance of a class over multiple contexts in C#?

I'm trying to write a console RPG game in C#. I have a Party class containing a list of Heroes, PlayerTeam. I instantiate the Party class PlayerTeam in my static void Main(string[] args, and I am trying to write a new function creating an encounter with an enemy. However, when I try to reference the Party class instantiated in the Main function, I am thrown an error stating The name 'PlayerTeam' does not exist in the current context. Any help is appreciated.
Welcome! Since a Main method is always static, any non-local variables referenced in the Main method must also be static. Mark your PlayerTeam variable as static.
// change this:
// public Party PlayerTream
// to this:
public static Party PlayerTeam;
Longer term, you will want to create some sort of Game object and have it create all of your state, rather than having static variables all over the place.
You need to move the declaration of PlayerTeam from inside your Main() method out to CLASS level so that it is accessible from anywhere:
public static Party PlayerTeam;
public static void Main(string[] args)
{
PlayerTeam = new Party();
}

Can I using main(string[] args ) function from 1 project to another project? [duplicate]

I would like to abstract some program logic to a base class for executing a command-line program (functionality similar to what this question was requesting).
in other words, something like this:
public abstract class BaseProgram<T>
{
public static void Main(string[] args)
{
Console.WriteLine(typeof(T));
}
}
public class Program : BaseProgram<string>
{
}
It is important to note that BaseProgram is in a different assembly.
This, however, does not work. The static void Main(string[] args) method must be in the derived class. Can anyone explain why that is? After all, the following is totally 'legal':
Program.Main(null);
BaseProgram<string>.Main(null);
and will output:
> System.String
> System.String
What I would like to know: are there any documented reasons for this outcome?
As was eventually disclosed during the commenting of the other answer, your BaseProgram<T> class is in a different assembly from the one you are trying to execute. The entry point of an assembly has to be in that assembly.
To do otherwise is like giving someone a key and telling them that's the key to your house's front door. Except the key is actually for some other completely different house's front door, so when they show up at your house it does them no good.
If you want to use the BaseProgram<T>'s Main() method, you need to delegate to it. For example, in your own assembly:
static class Program
{
public static int Main(string[] args)
{
return BaseProgram<string>.Main(args);
}
}
Note that for static types or static members of types, there's no need to actually inherit the base type, since you just invoke it via the actual type name instead of an instance reference.
I think the problem is that BaseClass is generic. In order to call main you have to supply a type argument, so which type should the system choose to call this method? Ofcourse it can't make random choices so this is illegal.
I found this in C# 5.0 Language Specification in 3.1 Application Startup
The application entry point method may not be in a generic class declaration.

Static/Non static classes and methods

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.

Why do static methods need to be wrapped into a class?

Sorry for the unlearned nature of this question. If there's a simple answer, just a link to an explanation will make me more than happy.
After 6 months programming I find static classes to be somewhat useful for storing routines that apply to many different classes. Here's a simplified example of how I use static classes, it's a class for parsing text into various things
public static class TextProcessor
{
public static string[] GetWords(string sentence)
{
return sentence.Split(' ');
}
public static int CountLetters(string sentence)
{
return sentence.Length;
}
public static int CountWords(string sentence)
{
return GetWords(sentence).Length;
}
}
And I use this in obvious ways like
class Program
{
static void Main(string[] args)
{
string mysentence = "hello there stackoverflow.";
Console.WriteLine("mysentence has {0} words in it, fascinating huh??", TextProcessor.CountWords(mysentence));
Console.ReadLine();
}
}
My question is: Why is it necessary to wrap these static methods in a static class?
It seems to serve no purpose. Is there a way I can have these methods on their own not wrapped in a class? I know encapsulation is beneficial but I don't see the use for static methods wrapped in static class. Is there something I am missing stylistically or otherwise? Am I completely barking up a silly tree? Am I thinking too much?
In C#, any method has to be declared inside a class. That's just how the language is specified.
A static class is actually more akin to a module than a class, so I too think you should be able to either:
define a function outside a class or;
import a module the same way you import a namespace (with using)
VB.NET, F# and Nemerle actually allow you to declare modules and import them; what allows you to use their methods unqualified.
This is valid Nemerle:
using System.Console; // import static methods in the Console class
class Hello {
static Main() : void {
WriteLine("Hello, world!"); // unqualified access!
}
}
Also, take a look at extension methods, they might allow you to "solve" this in a different way. The methods in your TextProcessor are begging to be string extension methods.
This post by eric lippert gives a pretty detailed explanation. I'm not sure if this guy "eric" knows what he's talking about or not though ;-)
It would be somewhat awkward to have methods just dangling around in a random namespace.
I suspect the answer is to provide "scope". Just because a method is static, doesn't mean it doesn't have a scope. It can still access other static private methods or member variables - and the class provides a "home" for these things to live in.
Static classes can also have static constructors that get called the first time a static method is used, so this provides the ability to set stuff up as needed.
It's more of an organizational design than anything to due with technical limitations.
A static method is a method called in a single instance of a class that is created at run-time.

C# Beginner, writing/calling a Method

When we write a method, say an easy one like
void myMethod()
{
// code here
//
}
and we call it from within Main(), it's done essentially this way:
Program myProgram = new Program ();
myProgram.myMethod();
Obviously, myProgram is entirely arbitrary (taking into consideration, of course, coding conventions) but what's up with the reference to Program?
You are declaring your method myMethod inside a class called Program. Since your method is not a static method (i.e. it is not static void myMethod()) it requires an instance of Program in order to work. Therefore you need to create a new instance of Program in order to invoke myProgram.myMethod() on it. If myMethod were static, you could have called it simply by Program.myMethod() or, since you're already inside that class to begin with, myMethod() (since the current class name is implied for static methods).
Program is a class, which contains methods. By default the only method it contains is static void Main(...).
If you add your non-static method myMethod it doesn't belong to the class Program, but rather to instances of Program (called objects).
Static methods (like Main) can be called directly from the class:
Program.Main(...);
Non-static methods must be called from objects of the class:
Program program = new Program();
program.myMethod();
Classes are designed to group together like functionality. Program isn't a good place to put these. You should create other classes, and use them throughout your code.
By using classes you keep like code together, and provide a mechanism to reuse the same code over again from different places. You can create as many different instances of 'Program' as you like, from many different classes, and invoke the 'myMethod' method on each of them.
For instance you might have a ClassRoster and a Student class, which can be used like this in the ClassScheduler class:
ClassRoster roster = new ClassRoster();
Student studentOne = new Student();
studentOne.StudentId = "123456";
roster.EnrollStudent(studentOne);
Program is the type, that defines myMethod in your question. In C# methods are defined by types.
You can either call methods via an instance of the defining type or via the type itself (if the method is static). Since myMethod isn't static, you need an instance of the type Program to call it.
use this:
public void myMethod()
{
// code here
}
in main method:
Program myProgram = new Program();
myProgram.myMethod();
Thanks everyone.
I went back to my code; I added static in front of myMethod, and in doing so the Program myMethod = new Program() became unnecessary (uncompilable? illegal?), and it can be called simply by writing myMethod() Obviously I need to study up on what static does and how it affects methods/classes!
I'm actually only in week #3 of my .NET class... our instructor, while very smart, leaves something to be desired in the teacher category. The assigned text for the class is only so-so in my opinion, at least for me and how I learn (Programming C#, O'Reilly) This is a very good community, thanks!

Categories