Passing Parameters, Class Scope Variables
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: Passing Parameters, Class Scope Variables

  1. #1
    Join Date
    Apr 2012
    Posts
    2

    Passing Parameters, Class Scope Variables

    How do you declare a variable and have it carry over between methods? I'm a beginner and no one seems to answer this question fully. I know I can use class scope variables, but how do I do that? Can you even declare public variables inside a method? If so, how? And someone mentioned passing parameters, how do I do that?

    So many questions, sorry.

  2. #2
    Join Date
    Jan 2010
    Posts
    1,099

    Re: Passing Parameters, Class Scope Variables

    This is some fundamental stuff - you should find enough info on the web.
    Here are a few tips to get you started.

    A class is essentially a definition of some custom type. It simply means that a class represents some concept or a set of values, by doing two things: providing a way to store some data about that concept, and providing a set of methods to manipulate that data.
    It does so on a higher level; e.g. the DateTime class doesn't represent some specific date & time, but rather the concept of date & time itself - the instances of the class (a.k.a. objects) are the actual, concrete date/time values. These are the values you assign to variables.

    So, the class simply enables you to treat all date/time values the same way. For example, two variables can store different date/time objects, but since they belong to the same class (same type), you can "ask" both of them to tell you say, what month they store, in the same way.
    That's why people commonly describe classes as blueprints for objects.
    The classes define concepts, the objects are the actual, specific instances of those concepts.

    OK. Now, this is a basic structure of a class (the order of class members is not really relevant, but it's good to follow some standard):
    Code:
    public class ClassName
    {
        // class data (fields)
        // class operations (methods, a.k.a. functions)
    }
    Class fields are essentially class level variables.
    For instance fields (non-static fields), each instance (object) of the class maintains its own set those data fields - this allows you to represent different instances of the same concepts (different dates in the example above).

    Methods of a class all have access to class fields, since they are defined in an enclosing scope (the class, between '{' and '}'). Think of scope as of a cardboard box. Class scope is a big box, with a lot of fields and methods inside, and each method is a box itself, since it has its own scope. Anything declared in the outer scope is visible in the inner scope, but not vice versa.

    So, how are the fields and the methods declared? Like this:
    Code:
    public class AnnoyingClass
    {
        // the fields - should be private, can have default values
        private int repeatCount = 1;
        private string message = "Hi, there!";
    
        // The methods.
        // Some should be public, some should 
        //  be private (for internal processing).
    
        // This method is special - it's used to create an object of a class.
        // It's called a constructor, and it has a same name as the class, 
        // and no return type specified. There can be more than one of these.
        public AnnoyingClass(string msg, int cnt)
        {
            message = msg;
            repeatCount = cnt;
        }
    
        // This method prints the message repeatCount-times.
        public void Print()
        {
            for (int i = 0; i < repeatCount, ++i)
            {
                Console.WriteLine(message);
            }
        }
    }
    Now, a few comments on that. All the important information you need is available above.
    The Print() method, or any other method defined on the class, can access the class fields, since they have class-scope.

    Let's now examine the anatomy of a method:
    Code:
        public return_type MethodName(parameter1, parameter2, ...)
        {
            // method body: method code goes here
        }
    So a method has a return type (unless it's a constructor), a unique name, a parameter list, and a method body that actually does the work.

    Constructors don't specify return types because they construct and "return" the objects.
    The Print() method in the example has the return type of void, since it doesn't return anything. A method can return an object of any type/class, provided that the type of the object and the return type of the method matches.

    The Print() method has an empty parameter list, but the constructor up there doesn't. Variables can be passed to it, and this is used to initialize the object. (Note that, without the default constrictor, which takes no arguments, the default values I specified for the fields make no sense).

    Somewhere in code, say, in Main(), you would create an object of your class like this:
    Code:
    AnnoyingClass annoyingKid = new AnnoyingClass("Are we there yet?", 300);
    
    
    // OR, alternatively, something like this:
    
    String question = "Are we there yet?";
    int numTimes = 300;
    
    AnnoyingClass annoyingKid = new AnnoyingClass(question, numTimes);
    In both cases, you are passing values, or variables that hold them, as parameters to the constructor.

    Then you can call the Print() method:
    Code:
    annoyingKid.Print();
    It will print out "Are we there yet?" 300 times.
    If Print() accepted any arguments, you would put them between the '(' and ')', in the specific order, as declared.

    That's the basics of it. I left out some details, like static members, method overloading, etc. You should read up on those too.

    One more thing: you asked if it was possible to declare a public variable local to the method. No, since the public/protected/private access modifiers don't make sense in method-scope. These are applied to class members (fields and methods), but not local variables. They specify what's visible from the outside, to the user of class instances. Classes themselves can have an access modifier, and this affects visibility on the assembly level (for example, if a class is available to be used from a dll). Since local variables exist only as long as the method is executing, you can't expect them to be used from the outside - they are short lived.

  3. #3
    Join Date
    Apr 2012
    Posts
    2

    Re: Passing Parameters, Class Scope Variables

    Thanks so much for all the info, but then how do you pass any information from one method to another? Like settings, etc.?

  4. #4
    Join Date
    Jan 2010
    Posts
    1,099

    Re: Passing Parameters, Class Scope Variables

    You either use one method to modify a class field, and then access it from another method (internal class opertions), or return a value of a certain type from one method, and then pass it as a parameter to a different method. Of course, the other method has to be able to take a parameter of that particular type.

    As I said, read up a bit on the basics, and then experiment in the Visual Studio a bit. It will become clearer when you try it.

  5. #5
    Join Date
    Jan 2010
    Posts
    1,099

    Re: Passing Parameters, Class Scope Variables

    P.S.
    I didn't exactly show you how to return a value from a method, so here:
    Code:
        public class Test1
        {        
            private Random rnd = new Random();   // a random number generator
    
            public int ModifyValue(int input)
            {
                int result = input;     // local variable
                result = result + rnd.Next(-100, 100);
    
                return result;  // this is how you return from a method
            }
    
            public void PrintValue(int value)
            {
                Console.WriteLine(value.ToString());
            }
        }
    Usage:
    Code:
                Test1 t = new Test1();
                int val = t.ModifyValue(1234);  // get the return value from the method, and
                t.PrintValue(val);              // pass it to another method

    If you want to use class-scope variables (fields) instead, then do something like this:
    Code:
        public class Test2
        {
            private int testValue = -1;
            private Random rnd = new Random();   // a random number generator
    
            public void ModifyTestValue()
            {
                testValue = rnd.Next(0, 100);    // accesses and modifies the testValue field
            }
    
            public void PrintTestValue()
            {
                Console.WriteLine(testValue.ToString());    // accesses the same testValue field
            }
        }

    Usage:
    Code:
                Test2 t = new Test2();
                t.ModifyTestValue();    // modifies the internal testValue field
                t.PrintTestValue();     // prints the internal testValue field
    Finally, I forgot to mention you should also learn about properties. They look like data, but they are actually a get/set method pair under the hood.
    Make sure to learn about the regular C# properties, and not just about the auto properties.

  6. #6
    Join Date
    Jan 2010
    Posts
    1,099

    Re: Passing Parameters, Class Scope Variables

    In response to a PM:
    Quote Originally Posted by jensenalex
    [...]
    I'd like to know if there's a way for me to declare an object in class scope?
    Yes. Class fields are, as I said, essentially nothing but class-level variables. They can have be type you like, and this can represent object of any class.
    Everything in C# are objects. Even when you're working with the fundamental types (like bool, int, float, string...), you are working with objects of those types.

    In the last example above, both of these lines declare objects in class scope. These are instance members (each object maintains a separate copy).
    Code:
           private int testValue = -1;
           private Random rnd = new Random();   // a random number generator
    If your question was about weather it's possible to declare an object of a certain class within that same class, the answer is - yes. This can be used in various ways. For example, a node in a link list might store a reference to the previous and the next node. (Most other languages would use pointers, but C# has reference types.) Another example is the Singleton Pattern - a language-independent design pattern used to make sure only a single instance of a class exist in the entire application. In this patter, the class maintains a private static class-level variable that represents the single instance, and provides a public static method that enables all the other objects to obtain it. (Static members are shared among all objects of the class; in a sense, they belong to a class, and in C# you can access them only via the class name. See the Math class to see what I mean - it only has static members.)
    Look up: C# type system, and static members.

    This is how you would declare static fields (can be private/internal/public):
    Code:
           private static int testValue = -1;
           private static Random rnd = new Random();   // a random number generator
    Each object would share these.
    If you created two objects of Test2 class, and called the ModifyTestValue() method on one, the PrintTestValue() method would display the same modified value for both objects.


    If you meant something else, can you explain a bit more?
    Last edited by TheGreatCthulhu; April 20th, 2012 at 10:40 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center