[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

C# Static, Public, Private

Posted on 2014-08-10
5
Medium Priority
?
467 Views
Last Modified: 2014-08-11
I have some experience in VB.NET.  I'd like to learn C# - but there are some concepts that I can't quite get my head around.  The current issue is Static vs Public vs Private when dealing with functions.

Take the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Variables
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 24;
            AddFive(ref number);
            Console.WriteLine("This is the number...: {0}", number);

            Console.ReadLine();
        }

        public void AddFive(ref int theNum)
        {
            theNum += 5;
        }


    }
}

Open in new window


The error I get is "An object reference is required for the non-static field, method or property 'Variables.Program.AddFive(ref int)"

So I need help understanding this error - how do I do an object reference from inside itself?
If AddFive is a method of Program, perhaps me.AddFive would work?  (it doesn't)

It seems that Public and Private are used inside instantiated classes, while static is in the main class - but for some reason (maybe it's my procedural upbringing), it doesn't seem right.

I know that changing "public void AddFive" to "static void AddFive" will fix the error - but I don't understand why.
I understand public and private (for the most part) from working with VB.NET - but static, not so much.  

In my main class (Program), I've learned I have to have "static void Main(string[] args)" as an entry point to my program - so does that mean that ANY and ALL functions in my main class also have to be static?

Any help you can provide on the subject is appreciated.  I did do a search on Google - but the responses I saw were basically "that's just the way it is" - and that's not super helpful.

Thank you for your time!

-Steve
0
Comment
Question by:slightlyoff
5 Comments
 
LVL 34

Assisted Solution

by:Mike Eghtebas
Mike Eghtebas earned 664 total points
ID: 40252340
This is my reply to part of it as I am reading through:
    class Program
    {
        static void Main(string[] args)
        {
            int number = 24;
            AddFive(number);
            Console.WriteLine("This is the number...: {0}", number);

            Console.ReadLine();
        }

        static public void AddFive(int theNum)
        {
            theNum += 5;
        }

Open in new window


1- not need to have Ref with AddFive(number); or AddFive(int theNum)
2. From a static method, you can call other method that are static also thus (static public void AddFive(int theNum)).

3. static, public, private, and protected:
-Public method in an instantiated object is accessible to the user.
-Private method in an instantiated object is not accessible to the user. It is only accessible to the other methods inside that class:
-Protected methods (I think) is available outside of the class but withing the same namespace (I guess it is known as packages say in java).

- static methods and static properties sort of break boundaries and has wider accessibility outside a class. Say you have Car class with property like:

Static int mileage(get; set;}

After instantiating myCar1 and myCar2, You can do the followings:

 myCar1.mileage=100;
myCar2.mileage=200;

but now reading
var mileage = myCar1.mileage;

will give you 200;
0
 
LVL 29

Assisted Solution

by:Paul Jackson
Paul Jackson earned 668 total points
ID: 40252350
static classes in C# are the same as shared classes in VB.net if you have experience of using them.

If a class method is not static/shared then the class has to be instantiated in order to call the method.
In your example above you would normally have all the classes as static as there is no reason to need to instantiate an instance of the class in order to call the method.
Classes should only me instantiated when they have properties that will be changed by a call to a class method.
This is because you may want to have multiple instances of the class instantiated at once.

Hope that helps.
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 668 total points
ID: 40252360
First, static is the equivalent of Shared in VB.NET. Next, anything defined as static can be referenced from any instance members, be they private or public. Conversely, static members *cannot* refer to instance members. The reason why is because static members are associated with the class itself, not a particular instance of a class. static members are a way of saying, "This thing is related to class XXXX, but it doesn't really mean anything per instance."

An example of such an occurrence is the AppDomain class and its CurrentDomain property. An AppDomain is a container for your code while your program is executing. So, there is at least one instance of an AppDomain in existence while your program executes. Now, it wouldn't make much sense for each instance of an AppDomain class to have a CurrentDomain property. So the CurrentDomin is defined as static, and so it is associated with the class itself. Any instance of the class can inspect this property to see what the current domain actually is, but the property itself cannot access anything to do with one of those specific instances (other than the one that it itself points to).
0
 
LVL 34

Expert Comment

by:Mike Eghtebas
ID: 40252374
Hi kaufmed, I didn't see your comment. Otherwise I would have kept quite.

Mike
-------------------
Steve,

I commented to the best of my knowledge which is not much. So, please wait until the good experts add more comments and do any necessary correction.

BTW, regarding: "will give you 200; " from above post.

You may also reference this same static property by the class name Car as in:

Car.mileage = 500;   now   var mileage = myCar1.mileage;  will give you 500.


Thank you,

Mike
0
 
LVL 1

Author Closing Comment

by:slightlyoff
ID: 40253101
Thank you all for your help.  I split the points because all three responses helped.  
I appreciate your time - I think i'm getting it. :)
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses

825 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question