Learning CSharp basics part-2 methods



Calling or invoking the methods in dotnet

Use the format ClassName.MethodName() to call a method. The . symbol is to access methods defined on the class. () symbols are the method invocation operators. Methods might accept no parameters or multiple parameters. Methods might return a value after completing task or return nothing (void).


Return value: It’s a value type returned by a method.
input parameters: Value types (or variables) inside a method.
overloaded method: It is a method that supports several implementations of the method, each with a unique method signature.


Stateful versus stateless methods

Stateful methods keep track of what’s happening in the program as it runs line by line, storing information in variables along the way. These stored information represents the current state of the program. In contrast, stateless methods don’t remember past actions or store any information between runs, for example “Console.WriteLine()“.


Creating new instance of a class

You don’t need to create a new instance of stateless classes. Calling stateful methods, requires creating new instance of the class using the new keyword and storing them in a variable. All methods on that class are available to the newly created object.

Random dice1 = new Random();

// in latest version of .net runtime
Random dice2 = new();

// Now you can access "Next" mothod from the Random class
int roll = dice2.Next(1, 7);

Here’s what the new operator does:

  1. It reserves memory in the computer to hold the new object.
  2. It creates the new object and stores it in the reserved memory.
  3. It returns the memory location where the object is stored, allowing you to save it in a variable like dice.



Tags: