0

As far as I know, to access any function, method or member of a class, we need to use its corresponding object, but in C#, we generally use a class Console without any object to access its functions like:

Console.WriteLine();

So, what is the reason for this. I am pretty confused about the direct use of the Console class without any object. Please, if anybody can help, solve this dilemma for me.

Vaibhav Kumar
  • 61
  • 1
  • 4
  • 4
    See: "`static` methods": https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members; as for "why does `Console` use `static` methods?": you only have one console/stdin/stdout/stderr – Marc Gravell Feb 14 '19 at 12:39

2 Answers2

-1

WriteLine is a static method, static method belongs to the class rather than object of a class.

Kevin Smith
  • 13,746
  • 4
  • 52
  • 77
-2

WriteLine() is static and can be called by it's classname Console.

In this example there is a Method() which has to be called on an instance of the class:

public class ExampleClass
{
    public static void StaticFunction()
    {
        Console.WriteLine("You can call me from my class-name");
    }

    public void Method()
    {
        Console.WriteLine("I'm called on an object.");
    }
}

public static void Main(string[] args)program..
{
    ExampleClass.StaticFunction();

    ExampleClass exampleObject = new ExampleClass();

    exampleObject.Method();
}
kara
  • 3,205
  • 4
  • 20
  • 34