Okay so about a year ago I took a usual college class on C# and since have been addicted to the language, I love writting in it. But I have been puzzled by an issue that I have never figured out, and I decided it's finally time to ask for some help.

Okay so call me a noob, but I have no clue what the purpose is for 'static' when it comes to programming (yeah I know sad), and that has to deal with the issue I am having. I learned about delegates from my class (which I think are awesome by the way). But for some reason when ever I call a class from a Form class I have to add a bunch of the word static into the code. Here's an example, of what I have to do to call a class from a Form class (sorry if this look weird I copied it from a code I have in the works, where I finally had to ask about this)

//----------------------------------------------------------------
namespace PeriodicTable1v3
 {
  public delegate object [,] readInFile();
 }
//----------------------------------------------------------------
namespace PeriodicTable1v3
 {
  public partial class Form1 : Form
   {
    static readInFile readInFileCall = new readInFile(readInExcel1.readInFile);
    //had to add static here

    object [,] values = readInFileCall();

    //....bunch of code 
   }
  //... bunch of code
 }
//----------------------------------------------------------------
namespace PeriodicTable1v3
 {
  public class readInExcel1
   {
    static Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
    //had to add static here (a variable I use both method in this class)

    public static object [,] readInFile ()
     {
      //had to add static here

      //...bunch of code

      values = gatherInfo(excelFile);
  
      //...bunch of code
     }
    public static object [,] gatherInfo (Workbook excelFile) 
     {
      //had to static here

      //...bunch of code
     }
//----------------------------------------------------------------

I hope this makes sense, this is an actual code (now granted I just added the statics for the example, but I know that I have to do this to make it work). Hopefully this small version works, cause the full version is over 500 lines of code.

This is something that has bugged me for along time and I finally decided I need to ask for some help (also if someone would enlighten me why I use 'static' period, as I have never understood what it's for, again I know that seems like a stupid thing to say but it's the truth, i only use it if the program won't compile until I add it)

Edited 5 Years Ago by JOSheaIV: n/a

Please read the information at the above link first to give you an idea of what static classes are.

Hopefully this has allowed you to realise that static classes in abundance are also bad ;)

The reason that you won't be able to make them work is probably because you're trying to do something like this.

void GetMyFile()
{
Object [,] myObject = readInExcel1.readInFile();
}

Now, that class hasn't been instantiated meaning there is no where for the program to goto to run that method. readInExcel1 is a class, not a variable and the method you called has not been marked as static.

In order to make it work without the static methods, you must make an instance of the class

pulic class MyApp
{
    static void Main()
    {
        // Instantiate a copy of the readInExcel1 class as excelClass
        readInExcel1 excelClass = new readInExcel1();
        // Call my non-static method
        Object [,] myObject = excelClass.readInFile();
        /* Do Stuff */
    }
}

I have a basic tutorial on C# classes on the forum Here

HMMM, then what's the purpose of use delegates? I thought delegates made it so I didn't have to declare the class?

Thanks by the way

Edited 5 Years Ago by JOSheaIV: n/a

Delegates are used mainly for callbacks and event listeners. They're a bit like function pointers I guess in that they're a "type" which references a method.
You typically call a delegate when you're multi-threading, but this isn't the only use for them.

See the MSDN Article for more information.

Okay then answered me one more question please, what's so bad about static then? I mean I call some of these classes mutliple times, is it better to keep this delegate call or make a new class and call it everytime?

A static class can be accessed from anywhere in the application and maintains the values you have given it.

This is bad in the sense that you now have no idea what values the class contains because any part of that running application can change it at any moment.

So say you have a class which decodes a binary file into ASCII characters and stores it in a string so you can access it later.

public static class MyDecoder
{
    public static String DecodedString;
    
    public static Boolean DecodeFile(String myFile)
    {
        /* Do stuff to get bytes from file */
        DecodedString = Encoding.ASCII.GetString(fileBytes);
        return !String.IsNullOrWhiteSpace(DecodedString);
    }
}

So what happens if you do this in your main application...

class Program
{
    static void Main(string[] args)
    {
        Thread parseBinaryDataThread = new Thread(new ThreadStart(ParseBinaryDataA));
        Thread parseBinaryDataThreadTwo = new Thread(new ThreadStart(ParseBinaryDataB));
        parseBinaryDataThread.Start();
        parseBinaryDataThreadTwo.Start();
        // Never ever use Thread.Sleep(), but here I need to to simulate work
        Thread.Sleep(2000);
        Console.WriteLine(MyDecoder.DecodedString);
    }

    static void ParseBinaryDataA()
    {
        MyDecoder.DecodeFile("dataFileA.dat");
    }
    
    static void ParseBinaryDataB()
    {
        MyDecoder.DecodeFile("dataFileB.dat");
    }
}

dataFileA.dat contains the string "Hello" in binary.
dataFileB.dat contains the String "World" in binary.

From the above, can you tell me what Console.WriteLine would print out?

There is a place for static variables and static classes. But they should only be used rarely and with great care. Instantiated classes should be the mainstay of any application with static classes converted into "Singletons" only where it is necessary.

Hope this managed to answer your question.


EDIT: Also, please don't confuse static classes and delegates. They are not the same thing ^^

Edited 5 Years Ago by Ketsuekiame: n/a

So you're saying that I were to access the same class as a static method while threading then it would be bad? Cause from what it looks like to me if I call the class in one place to read in a file at one and then call the class at another time to read a file, there should be no danger right? Atleast that's how see you saying it (never really learned threading, tried it once, didn't work, haven't tried since)

I mean you see how I used the delegates about right? I pretty much just split come of the program off into other class, but I don't need to worry about a constructor as most the time all the variable I need I pass in.

Am I looking at this completely wrong? Did I misinterpret something? Thanks for helping me understand this (oh and fyi this is not a school assignment I am asking about this is completely for my own fun)

You're misunderstanding what a delegate is.

I assume in your code you're simply calling a static method on the class. This is not a delegate. You're simply calling a method, your original method will stop execution until the method you called is returned. Whilst, fundamentally, there is nothing wrong with this, you should not get used to using static classes and methods for everything.

It is very bad design.

Also a static class has a static constructor but you don't have control over when it will be called (could be at program start, first use of the class, first use of a variable in the class etc.)

If you really think that the class should have a single instance and able to be used anywhere in your application, whilst retaining any previous values, convert it to a Singleton. Otherwise, convert it to a normal class and use instantiation.

This article has been dead for over six months. Start a new discussion instead.