10

In C#, is it possible to access an instance variable via a static method in different classes without using parameter passing?

In our project, I have a Data access layer class which has a lot of static methods. In these methods the SqlCommand timeout value has been hard-coded. In another class(Dac) in our framework there are many instance methods which call these static methods.

I don't want to code too much using parameter passing. Do you have any other solution which is easier than parameter passing?

1
  • A static method is not associated with any instance so how do you expect it to know which instance to access a member of? Commented Jul 30, 2010 at 13:38

5 Answers 5

14

Yes, it is possible to access an instance variable from a static method without using a parameter but only if you can access it via something that is declared static. Example:

public class AnotherClass
{
    public int InstanceVariable = 42;
}

public class Program
{
    static AnotherClass x = new AnotherClass(); // This is static.

    static void Main(string[] args)
    {
        Console.WriteLine(x.InstanceVariable);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

7

Sure, you could pass an instance as a parameter to the method. Like:

public static void DoSomething(Button b)
{
    b.Text = "foo";
}

But it wouldn't be possible to get at any instance variables otherwise.

Comments

6

A static method has no instance to work with, so no. It's not possible without parameter passing.

Another option for you might be to use a static instance of the class (Mark's example shows this method at work) although, from your example, I'm not sure that would solve your problem.

Personally, I think parameter passing is going to be the best option. I'm still not sure why you want to shy away from it.

1 Comment

The edit boils down to "I don't want to", which is not a good technical reason. The alternative is really really bad, if not impossible.
2

Yes it can, as long as it has an instance of an object in scope. Singletons for instance, or objects created within the method itself..

Take for example a common scenario :

public static string UserName
{
   return System.Web.HttpContext.Current.User.Identity.Name;
}

Comments

1

No you can't.

If you want to access an instance variable then your method by definition should not be static.

2 Comments

What about accessing instance properties of singletons ?
@Richard: With a singleton you have an instance, and the methods would not be static in that case. Only the method to get the singleton instance is static.

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.