Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
Switch Expression in C# 8.0
Next article icon

Static Local Function in C# 8.0

Last Updated : 06 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Static local functions introduced in C# 8.0. It is a local function created using the static keyword. This is used to prevent variables to captured from the enclosing. If a method is marked as static then we cannot access variables from the enclosing method. It enhances the performance by reducing the overhead of creating a closure.

Example 1: Demonstration of static local function in C#.

C#
// Simple C# program to illustrate  // the static local function using System;  class Geeks { 	public static void calc() 	{ 		int val = 10;        		// local function  		// can access val 		void local_greet() 		{ 			Console.WriteLine("Hello from local function"                                + val); 		}  		// Static local function  		// cannot access val 		static void static_greet() 		{ 			Console.WriteLine("Hello from static local function"                                + val); 		} 		 		// Calling local functions 		local_greet();                // calling static function  		static_greet(); 	}  	public static void Main(String[] args) 	{ 		calc(); 	} } 

Output:

StaticLocalFunctionOutput

Explanation: In the above code shows that the local function cannot directly access the variable val outside from the enclosing that prevents accidental captures of variables from the outer scope.


Example 2:

C#
// C# program to demonstrate regular and static local functions using System;   class Geeks {     // Method to demonstrate local and static local functions     public static void calc()     {         int val = 10; // Local variable          // Regular local function          // Can access 'val' directly from the enclosing method         void local_greet()         {             Console.WriteLine("local function has val: " + val);         }          // Static local function          // Requires a parameter to access external variables         static void static_greet(int v)         {             Console.WriteLine("static local function has val: " + v);         }                  // Calling static function with the parameter 'val'         static_greet(val);          // Calling the regular local function that accesses 'val' directly         local_greet();     }      // Main method to execute the calc function     public static void Main(String[] args)     {         calc();     } } 

Output:

StaticLocalFunctionWithOutput

Explanation: We can not directly access the val inside the static local function but we can pass the value as a parameter and then access it inside our static local function.

Local Function

The local function allows us to declare a method inside the body of an already-defined method. Local function is a private function of a function whose scope is limited to the function in which it is created. The type of local function is similar to the type of function in which it is defined. We can only call the local function from their container members.

Example:

C#
// Simple C# program to // illustrate local function using System;  class Geeks { 	public static void Main() 	{ 		// Here SubValue is the local 		// function of the main function 		void SubValue(int a, int b) 		{ 			Console.WriteLine("Value of a is: " + a); 			Console.WriteLine("Value of b is: " + b); 			Console.WriteLine("final result: {0}", a - b); 			Console.WriteLine(); 		}  		// Calling Local function 		SubValue(30, 10); 		SubValue(80, 60); 	} } 

Output:

LocalFunctionOutput

Local Function vs Static Local Function

Features

Local function

Static local function

Definition

A function defined inside another function.

A location function declare with static keyword.

Variable Access

Can access the variable outside from the enclosing.

Restricted to access the variable outside from the enclosing.

Performance

less optimized, create overhead while capturing variables.

Enhance performance because there is no overhead of closure.

Closures

It creates closure which results memory overhead.

It is not used to access the outer variables so It not create closure.



Next Article
Switch Expression in C# 8.0
author
ankita_saini
Improve
Article Tags :
  • C#
  • CSharp-8.0

Similar Reads

  • Local Function in C#
    The local function feature is introduced in C# 7.0. It allows you to declare a method inside the body of an already defined method. Or in other words, we can say that a local function is a private function of a function whose scope is limited to that function in which it is created. The type of loca
    4 min read
  • Switch Expression in C# 8.0
    The switch statement is a multiway branch statement. It provides an easy way to forward execution to different parts of code based on the value of the expression. So, with switch statement you always use some repetitive case and break keywords and also use default statement as shown in the below exa
    2 min read
  • C# | Static Class
    In C#, one is allowed to create a static class, by using static keyword. A static class can only contain static data members and static methods. It is not allowed to create objects of the static class and since it does not allow to create objects it means it does not allow instance constructor. Stat
    4 min read
  • Stack.Count Property in C#
    This method(comes under System.Collections namespace) is used to get the number of elements contained in the Stack. The capacity is the number of elements that the Stack can store and the count is the number of elements that are actually in the Stack. The capacity is always greater than or equal to
    2 min read
  • Static keyword in C#
    static is a modifier in C# which is applicable for the following: ClassesVariablesMethodsConstructorIt is also applicable to properties, event, and operators. To create a static member(class, variable, methods, constructor), precede its declaration with the keyword static. When a member is declared
    4 min read
  • Default Interface Methods in C# 8.0
    Before C# 8.0 interfaces only contain the declaration of the members(methods, properties, events, and indexers), but from C# 8.0 it is allowed to add members as well as their implementation to the interface. Now you are allowed to add a method with their implementation to the interface without break
    5 min read
  • Aggregation Function in LINQ
    In LINQ, aggregation functions are those functions which are used to calculate a single value from the collection of the values. Real life example of aggregation function is calculating the annual rainfall occurred in 2018 according to readings collected whole year. Another example, the sum function
    3 min read
  • List FindLastIndex() Method in C# | Set -1
    This method is used to search for an element which matches the conditions defined by a specified predicate and returns the zero-based index of the last occurrence within the List<T> or a portion of it. There are 3 methods in the overload list of this method: FindLastIndex(Predicate<T>) M
    3 min read
  • Null-Coalescing Assignment Operator in C# 8.0
    C# 8.0 has introduced a new operator that is known as a Null-coalescing assignment operator(??=). This operator is used to assign the value of its right-hand operand to its left-hand operand, only if the value of the left-hand operand is null. If the left-hand operand evaluates to non-null, then thi
    3 min read
  • Stack.GetEnumerator Method in C#
    This method returns an IEnumerator that iterates through the Stack. And it comes under the System.Collections namespace. Syntax: public virtual System.Collections.IEnumerator GetEnumerator (); Below programs illustrate the use of above-discussed method: Example 1: // C# program to illustrate the //
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences