tags:

views:

112

answers:

5

Hi,

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 SqlCommand timeout value has been hard-coded. In another class(Dac) in our framework there has been many instance methods which calls these static methods. I don' t want to do many coding with using parameter passing. Do you have any other solution which is more easier than parameter passing.

Thanks

+2  A: 

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.

Jake Pearson
thanks Jake, but I changed the question.
mkus
+5  A: 

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.

Justin Niessner
justin, I edited my question for your interest.
mkus
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.
siride
+8  A: 

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);
    }
}
Mark Byers
+1, but oh [the horror of global variables](http://c2.com/cgi/wiki?GlobalVariablesAreBad)!
Jeff Sternal
yes...brings forth memories of childhood nightmares!
Peter Lillevold
+1  A: 

No you can't.

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

Brian R. Bondy
What about accessing instance properties of singletons ?
Richard Friend
@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.
Brian R. Bondy
+1  A: 

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