• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 179
  • Last Modified:

C# basic doubt

I have 2 functions in a class

class test
{
      function a()
      {
            set values to class shape
      }

      function b()
      {
            color = shape.color
      }
}

In function b() want the value of shape class which was set in function a()
0
Rahamathulla_J
Asked:
Rahamathulla_J
  • 2
1 Solution
 
RytmisCommented:
This assumes you already have a Shape class with a Color property:

class test
{
     private Shape myShape;

     function a()
     {
          myShape = new Shape();
          myShape.Color = SomeColor;
     }

     function b()
     {
          Color color = myShape.Color;
     }
}

0
 
Rahamathulla_JAuthor Commented:
My problem is i am not able to declare myShape in the functon b. I hope i didnt declare globaly

private Shape myShape;

Am i right?
0
 
ozymandiasCommented:
class test
{

     // declare shape
     private Share myShape;

     public test(){
          // instantiate shape
          myShape = new Shape();
     }

     function a()
     {
          set values to class shape
     }

     function b()
     {
          color = myShape.color
     }
}
0
 
RytmisCommented:
If you declare myShape in function scope, you can't expect to get to it outside that function's scope. Instance variables are not global in scope, but are avaiable to all instance methods of a class.

Ozymandias' example instantiates myShape in the constructor so you don't have to do it in a() or b() but both can still access it.
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now