What's the difference between constructor and method?

Mikhail 21 Reputation points
2021-11-24T20:43:37.423+00:00

Hi, what is a constructor in c#? I've been trying figure out what's the difference between a constructor and a normal method. I'm a beginner.

Developer technologies | C#
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2021-11-25T01:54:29.677+00:00

    Hi @Mikhail ,
    You can refer to Constructors (C# programming guide) for more information.
    And here are some characteristics of the constructor.

    • A constructor is a special method whose name is the same as the name of its type. Its method signature includes only the method name and its parameter list; it does not include a return type.
    • The constructor is used to initialize the members of the object, and can complete some work while creating an object. When using new() to create a new object, the system will automatically call the constructor of the class.
    • When no construction method is written in a class, the system will automatically generate a construction method without parameters when compiling, but if you write a construction method yourself, the system will not automatically generate it again.

    Best Regards.
    Jiachen Li

    ----------

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Petrus 【KIM】 546 Reputation points
    2021-11-25T01:46:40.77+00:00

    REF.

    [Constructor]
    https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors

    [Method]
    https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/methods

    A constructor is executed when you create an instance of a class.
    A method is executed by explicitly calling its name.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.