Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we access static method through the object in .net

Tags:

c#

with the following code:

public class test
{
    public static void DoSomething()
    {
        Console.WriteLine("test");
    }
}

public class test2
{
    public test2()
    {
        var a = new test();
        a.DoSomething(); // invalid
        test.DoSomething(); // is valid
    }
}

I need to access the static method through the base class, and not through the instance.

But, what would have been the downside of letting the user access it through the instance? It seems to me that it would help with readability.

like image 325
Thomas Avatar asked Mar 04 '23 18:03

Thomas


1 Answers

You can't call a static method from a class instance, because all static fields and methods are associated with the type rather than an instance of said type.

For a deeper understanding of static classes I suggest you read this.

like image 154
cmos Avatar answered Mar 15 '23 22:03

cmos