Welcome to Blogs @ Andrew Qu
Blog Index
All blogs
Search results

C# Local Function


C# local functions can be used in a method locally to repeat operations. It can access all variables defined in the parent method.


C# local functions can be defined using this syntax:

Func <T..., TResult> FuncName = (T t, ...) =>
   return TResult;
Local function has the same scope as the parent method. It can therefore access all local variable, class members and arguments. Local functions can be used to repeat operations that is only used within the parent method.

An example

public Point3D[] GetExtents(Rect[] rects, Circle[] circs)
   double xmin, xmax, ymin, ymax;
   xmin = ymin = double.MaxValue;
   xmax = ymax = double.MinValue;

   Func<double, double, bool> UpdateExtent = (double x, double y) =>
      if (x < xmin) xmin = x;
      if (x > xmax) xmax = x;
      if (y < ymin) ymin = y;
      if (y > ymax) ymax = y;
      return true;

   // Do rectangles
   foreach (var rect in rects)
      UpdateExtent(rect.Left, rect.Bottom);
      UpdateExtent(rect.Top, rect.Right);

   // Do circles
   foreach (var c in circs)
      UpdateExtent(c.Center.X - c.Radius, c.Center.Y - c.Radius);
      UpdateExtent(c.Center.X + c.Radius, c.Center.Y + c.Radius);
   return new Point3D[] { new Point3D(xmin, ymin, 0), 
       new Point3D(xmax, ymax, 0) };
Ads from Google
Dr Li Anchor Profi
Engineering anchorage plate design system
©Andrew Qu, 2014. All rights reserved. Code snippets may be used "AS IS" without any kind of warranty. DIY tips may be followed at your own risk.