Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A way to get at non-static information from Static Context

Tags:

c#

I know you can't static members from instance members.

But lets say I have in one assembly this:

public class ClassA
{
    public List<order> GetOrders(int orderID)
    {
        ...
    }
}

Then in another assembly this:

public static ClassB
{
    private static void DoSomethingElse(int orderID)
    {
        List<order> orderList = ClassA.GetOrders(orderID);
        ...rest of code
    }
}

Is there any way to still get at that method in Class A some other way...some work around to this?

like image 209
PositiveGuy Avatar asked Jun 30 '10 19:06

PositiveGuy


3 Answers

You certainly can access static members from instance members... but you should understand why you can't access instance members without an instance.

Your class basically says that each instance of ClassA allows you to get a list of orders associated with a particular ID. Now, different instances of ClassA might give different results - for example, they might be connecting to different databases. Which results do you want to get in DoSomethingElse?

To give a simpler example, suppose we had a Person class, and each person had a name:

public class Person
{
    public string Name { get; set; }
}

Does it make sense to ask "What is Person.Name?" No - because you haven't specified which person you're talking about.

You should either make ClassA.GetOrders static - if it doesn't involve any per-instance information, including virtual members - or make ClassB aware of the instance of ClassA to use when finding out the orders.

If you could let us know more realistic names for these classes, we could give guidance as to which solution is more likely to be appropriate... personally I would generally favour the latter approach, as static members generally lead to less testable code.

like image 139
Jon Skeet Avatar answered Nov 05 '22 05:11

Jon Skeet


Not sure I got you right, but try new ClassA().GetOrder(orderID);

like image 21
STO Avatar answered Nov 05 '22 07:11

STO


I know you can't access static members from instance members and vice versa.

Actually you can.

public class MyClass
{
   public static void Foo()
   {
       Console.Write("Foo");
   }

   public void Bar()
   {
       Foo(); // Perfectly valid call
   }
}

But to go the other way (instance from static) you need to actually CREATE an instance:

public class MyClass
{
   public static void Foo()
   {
       MyClass c = new MyClass();
       c.Bar();
   }

   public void Bar()
   {
       Console.Write("Foo");
   }
}

You may be confusing static with it's meaning in different languages. In C# it means that the member is not bound to any specific instance of the class, you could in effect call the static member from the above examples like this:

MyClass.Foo();
like image 43
Aren Avatar answered Nov 05 '22 05:11

Aren