C# Methods, Structures, Classes, and Objects
Methods
- A method is a group of statements that accomplishes a specific task, invoked by its name.
- Syntax:
access_modifier return_type MethodName (parameter_list) {
//statement(s) in method body
}
- Key parts:
access_modifier: Visibility (e.g., private, public). Default is private.return_type: Data type of the returned value or void if no value is returned.MethodName: Case-sensitive identifier followed by parentheses.parameter_list: Type, order, and number of parameters.- Method body: Statements enclosed in curly braces.
- Method Signature: Includes access level, return type, method name, and parameters.
- Invocation: Use method name followed by parentheses and arguments.
- Arguments: Values passed to the method's parameters.
Method Overloading
- Methods with the same name can be declared in the same class if they have different parameter sets (number, types, or order).
- The CLR compiler selects the appropriate method based on the arguments.
Structures
- Value type data type to hold related data of various types.
- Keyword:
struct. - Cannot initialize struct fields directly; use a constructor.
- Structures are value types; classes are reference types.
- Structures can implement interfaces but cannot inherit from other structures.
- Syntax:
access_modifier struct StructName {
//structure members( fields, methods, and constructors)
}
Classes
- A blueprint that defines data and actions in a single unit; instances are called objects.
- Keyword:
class. - Instances are created using the
new keyword. - Members are accessed using the dot operator (
.). - Syntax:
public class Point {
//instance variables
public int xPos, yPos;
//constructor
public Point (int x, int y) {
this.xPos = x;
this.yPos = y;
}
public void displayPosition() {
Console.WriteLine("xPos = " + this.xPos + " yPos = " + this.yPos);
}
}
Encapsulation
- Hiding data from the outside world to prevent errors.
- Implemented by:
- Declaring data members as
private. - Accessing private members through methods or properties (get and set accessors).
- Syntax:
access_modifier datatype propertyName {
get { //get accessor code }
set { //set mutator code using value keyword }
}
The this Keyword
- Refers to the current instance of the class.
- Used to resolve ambiguity between data members and parameters.
Constructors
- Special method with the same name as the class or structure; initializes instance variables.
- Cannot return a value.
- Access modifier should be
public. - Overloading: Multiple constructors with different parameter lists.
- Syntax:
access_modifier ClassName (parameter_list) {
//statement(s) to initialize object
}
Namespace
- Provides a logical grouping to organize related types.
- Controls the scope of class and method names.
- Members are accessed using the
using keyword. - Syntax:
namespace name {
//namespace members
}