C# / C# Methods and Scope

Using Static and Instance Methods

This tutorial will guide you through the use of static and instance methods in C#. We'll discuss the differences and when to use each type of method.

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Explores methods, method overloading, and scope of variables in C#.

Introduction

In this tutorial, we'll be exploring the concepts of static and instance methods in C#. The goal is to understand the differences between these two types of methods and learn when to use each.

By the end of this tutorial, you will:
- Understand what static and instance methods are,
- Learn how to declare and use each type of method,
- Know when to use static or instance methods.

Prerequisites:
- Basic knowledge of C# programming language,
- Familiarity with object-oriented programming concepts.

Step-by-Step Guide

Understanding Static Methods

Static methods belong to the class itself and not to any instance of the class. They're declared with the keyword static and can be called directly on the class without creating an instance of the class.

Example:

public class MyClass {
    public static void MyMethod() {
        // Method body
    }
}

// Call the method
MyClass.MyMethod();

Tips for using static methods:
- Use static methods when the method does not depend on instance variables.
- Static methods can't access non-static class members.

Understanding Instance Methods

Instance methods are associated with an instance of a class. They can access instance variables and change their state. Instance methods are declared without the static keyword.

Example:

public class MyClass {
    public void MyMethod() {
        // Method body
    }
}

// Create an instance and call the method
MyClass myObject = new MyClass();
myObject.MyMethod();

Tips for using instance methods:
- Use instance methods when the method needs to access or modify instance variables.

Code Examples

Static Method Example

public class Calculator {
    public static int Add(int a, int b) {
        return a + b; // returns the sum of a and b
    }
}

// Call the method
int result = Calculator.Add(5, 3); 
Console.WriteLine(result); // Prints: 8

Instance Method Example

public class Calculator {
    private int _result = 0;

    public void Add(int number) {
        _result += number; // adds the number to the _result
    }

    public int GetResult() {
        return _result; // returns the current _result
    }
}

// Create an instance and call the methods
Calculator calculator = new Calculator();
calculator.Add(5);
calculator.Add(3);
Console.WriteLine(calculator.GetResult()); // Prints: 8

Summary

In this tutorial, we've learned about static and instance methods in C#. We found out that static methods are associated with the class itself, while instance methods are associated with an instance of the class.

For further learning, explore more about object-oriented programming in C#, including classes, objects, and properties.

Practice Exercises

  1. Create a Dog class with a static method Bark() which prints "Woof!" and an instance method Eat() which prints "Yum!".

  2. Create a Car class with a static method NumberOfWheels() which returns 4 and an instance method Drive() which prints "Vroom!".

Solutions:

  1. Solution to Exercise 1:
public class Dog {
    public static void Bark() {
        Console.WriteLine("Woof!");
    }

    public void Eat() {
        Console.WriteLine("Yum!");
    }
}

// Call the static method
Dog.Bark(); // Prints: Woof!

// Call the instance method
Dog myDog = new Dog();
myDog.Eat(); // Prints: Yum!
  1. Solution to Exercise 2:
public class Car {
    public static int NumberOfWheels() {
        return 4;
    }

    public void Drive() {
        Console.WriteLine("Vroom!");
    }
}

// Call the static method
int wheels = Car.NumberOfWheels(); 
Console.WriteLine(wheels); // Prints: 4

// Call the instance method
Car myCar = new Car();
myCar.Drive(); // Prints: Vroom!

Keep practicing with different scenarios to get a better understanding of when to use static and instance methods.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Image Converter

Convert between different image formats.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help