Methods and Constructors

Now I am learning C # and new to the programming world. I have a book called "Full Link" by Herbert Schildt. This is a good book so far, and I'm in the know about methods and constructors.

I am rather confused about the difference between methods and constructors. Because in the book she has almost the same example. I do not know how to distinguish them. I would appreciate your idea. By the way, I have several definitions here for both, I just wanted to know how to distinguish them.

thanks for the help

Greetings

+3
source share
12 answers

The constructor only works when creating a new instance of the class. This is the very first method to start an instance; it must be started and executed exactly once.

.

. , . . , - - .

. . , . .

public class MyType
{
    private SomeType _myNeeds;

    // constructor
    MyType(SomeType iWillNeedThis)
    {
        _myNeeds = iWillNeedThis;
    }

    // method
    public void MyMethod()
    {
        DoSomethingAbout(_myNeeds);
    }
}
+11

- .. , "" .

: - ++ #, , .

- -, . , .

About.com

+12

- - , . .

, , , , , .

+5

, . , . , , , - .

public class Foo
{
    // Constructor
    public Foo()
    { }

    public void Bar()
    { }
}
+3

, . , , , , . .

Public class person()
  {
     public person()
     {
     }
   }
+3

, . , , . , (). , return.

:

class Widget //Some Class "Widget"
{
    int _size;
    int _length;
// Declaring a Constructor, observe the Return type is not required

public Widget(int length)
    {
        this._length = length;
    }
// Declaring a Method, Return type is Mandator

    public void SomeMethod(int size)
    {
        this._size = size;
    }
}

//Calling the Constructor and Method

class Program
{
    static void Main()
    {

//Calling the Constructor, Observe that it can be called at the time the Object is created
        Widget newObject = new Widget(124);

//Calling the Method, Observe that the Method needs to be called from the New  Object which has been created. You can not call it the way Constructor is called.

        newObject.SomeMethod(10);I

    }
}
+3

, , . .

, . . (, , ).

: , , , #, , , OP . , , .

+2

, , . - , .

, , . . ( ).

0


- : , "object.weight ", " " ..

, , . , .

, .


, , . , , . #, , ++.

0

- , /

0

- . , , . , , .

0

- , . _ - , . . , . , , , .

0

Source: https://habr.com/ru/post/1712653/


All Articles