mkus
mkus

Reputation: 3487

Is it possible to access an instance variable via a static method?

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?

Upvotes: 10

Views: 41901

Answers (5)

Justin Niessner
Justin Niessner

Reputation: 245399

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.

Upvotes: 6

Richard Friend
Richard Friend

Reputation: 16018

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;
}

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838066

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);
    }
}

Upvotes: 14

Brian R. Bondy
Brian R. Bondy

Reputation: 347216

No you can't.

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

Upvotes: 1

Jake Pearson
Jake Pearson

Reputation: 27717

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.

Upvotes: 7

Related Questions