Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Static function explained

Status
Not open for further replies.

robert201

Programmer
Jul 18, 2007
80
TH
Hello,

I am just writing simple threading program in C# program, I am coming from VB.Net and just wondering why my WriteY() function has to be a static. I through this could be public or private.

Can anyone explain why it has to be a static.

Many thanks,

Steve

Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace App1
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread t = new Thread(WriteY);
            t.Start();
            while (true) Console.Write("X");
        }

        static void WriteY()
        {
            while (true)
                Console.Write("Y");
        }
    }
}
 
your main method is static. If your main method creates an instance of an object then you can use non-static methods. A static method can be both public or private it's just how you access it.

For example

public class Writer
{
public static void WriteY()
{
Console.WriteLin("Y");
}

public void WriteZ()
{
Console.WriteLine("Z");
}
}

From your main method you have to access those 2 properties in different ways.

static void Main()
{
Writer.WriteY(); //This is a static method
//Writer.WriteZ() is not available

Writer mywriter = new Writer();
mywriter.WriteZ(); //This is a non-static method
//mywriter.WriteY() is not available
}


I hope that gives you some light

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top