0

I'm a bit confused.

I have the following code:

public class MyClass
{
  public string DoSomething(string TheString)
  {
     int TheID;
     string TheString = "";
  }
}

This works fine; it compiles. However, why doesn't this work?

public class MyClass
{
  public string DoSomething(string TheString)
  {
     private int TheID {get;set;}
     private string TheString {get;set;}
  }
}

I want to make these variables private. What do I need to change?

1
  • properties cant not be part of methods. Its always part of class. Commented Dec 22, 2011 at 3:38

2 Answers 2

5

Private variables are only valid at the class level:

public class MyClass { 
   private int TheID {get;set;} 
   private string TheString {get;set;}

   public string DoSomething(string TheString)   {

   }
  }

Variables defined inside a method are local in scope and they only exist inside that method. Nothing outside the method can access them. It makes no sense to declare a local variable as private.

Sign up to request clarification or add additional context in comments.

2 Comments

Just a question : Why use private properties instead of use private members ?
@Florian, that was the example frenchie gave in his question. Normally it would be private fields instead of private properties.
2

They are scoped inside the method - you can't access them outside of it. You can think of them as being private.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.