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

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

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

I do not want too much code by passing parameters. Do you have another solution that is easier than passing parameters?

+7
c # static
source share
5 answers

Yes, you can access an instance variable from a static method without using a parameter, but only if you can access it through what is declared as 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); } } 
+11
source share

The static method has no instance to work, so no. This is not possible without passing parameters.

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

Personally, I think that passing parameters would be the best option. I'm still not sure why you want to dodge it.

+6
source share

Of course, you can pass an instance as a parameter to a method. How:

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

But otherwise, you will not be able to get any instance variables.

+5
source share

Yes, he can, if he has an instance of an object in scope. For example, singletones or objects created in the method itself.

Take, for example, the general scenario:

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

No, you can’t.

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

+1
source share

All Articles