C#: Function in Function possible?

C#.NetMethods

C# Problem Overview


Is it possible to declare a method within another method in C#?

For example like that:

void OuterMethod()
{
    int anything = 1;
    InnerMethod();     // call function
    void InnerMethod()
    {
        int PlitschPlatsch = 2;
    }
}

C# Solutions


Solution 1 - C#

Update: Local functions where added in version 7 C#.

void OuterMethod()
{
    int foo = 1;
    InnerMethod();
    void InnerMethod()
    {
        int bar = 2;
        foo += bar
    }
}

In previous version C# you have to use action like this:

void OuterMethod()
{
    int anything = 1;
    Action InnedMethod = () =>
    {
        int PlitschPlatsch = 2;
    };
    InnedMethod();
}

Solution 2 - C#

UPDATE: C#7 added local functions (https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#local-functions)

void OuterMethod()
{
    int foo = 1;

    InnerMethod();

    void InnerMethod()
    {
        int bar = 2;
        foo += bar
    }

}

In versions of C# before C#7, you can declare a Func or Action and obtain something similar:

void OuterMethod()
{
    int foo = 1;
    Action InnerMethod = () => 
    {
        int bar = 2;
        foo += bar;
    } ;

    InnerMethod();
}

Solution 3 - C#

yes, there are ways. With C# 3.0 you have the Func<T> type that does this.

For example, I wrote this yesterday:

  var image = Image.FromFile(_file);
  int height = image.Height;
  int width = image.Width;
  double tan = height*1.00/width;
  double angle = (180.0 * Math.Atan(tan) / Math.PI);
  var bitmap = new System.Drawing.Bitmap(image, width, height);
  var g = System.Drawing.Graphics.FromImage(bitmap);
  int fontsize = 26; // starting guess
  Font font = null;
  System.Drawing.SizeF size;

  Func<SizeF,double> angledWidth = new Func<SizeF,double>( (x) =>
      {
          double z = x.Height * Math.Sin(angle) +
          x.Width * Math.Cos(angle);
          return z;
      });

  // enlarge for width
  do
  {
      fontsize+=2;
      if (font != null) font.Dispose();
      font = new Font("Arial", fontsize, System.Drawing.FontStyle.Bold);
      size = g.MeasureString(_text, font);
  }
  while (angledWidth(size)/0.85 < width);

The purpose was to add a watermark to an existing image. I wanted to make the size of the watermark text about 85% of the width of the image. But I wanted to cant the watermark text so that it was written on an angle. This revealed the need to do some trig calculations based on the angles, and I wanted a little function to perform that work. The Func is perfect for that.

The code above defines a Func (a function) that accepts a SizeF and returns a double, for the actual width of the text when it is drawn at the given angle. This Func is a variable within a function, and the variable itself holds a (reference to a) function. I can then invoke that "private" function within the scope where I've defined it. The Func has access to the other variables that are defined before it, in its execution scope. So, the angle variable is accessible within the angledWidth() function.


If you want invokable logic that returns void, you can use Action<T>, in the same way. .NET defines Func generics that accept N arguments, so you can make them pretty complicated. A Func is like a VB Function or a C# method that returns non-void; an Action is like a VB Sub, or a C# method that returns void.

Solution 4 - C#

Five years have passed since this question was asked and now C# 7 is coming.

It's slated to include local functions, and is apparently already implemented.

> Local functions (Proposal: #259) [currently in future branch]

https://github.com/dotnet/roslyn/issues/259

Solution 5 - C#

The delegate keyword does just that.

void OuterMethod()
{
	var InnerMethod = delegate()
	{
		int PlitschPlatsch = 2;
	};

	int anything = 1;
	InnerMethod();
}

Don't forget that, per scoping, the PlitschPlatsch variable won't be accessible outside InnerMethod.

Solution 6 - C#

Take a look at anonymous methods. I think that's what you're looking for.

Solution 7 - C#

If you're looking mainly to "hide" a method that is just a "helper" ... another option is to make your helper(s) private. That way they don't become part of your class's public interface.

This has the advantage that the helper(s) can be reused if necessary; but it / they won't be "internal" to the calling method.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNonView Question on Stackoverflow
Solution 1 - C#JaredParView Answer on Stackoverflow
Solution 2 - C#jeroenhView Answer on Stackoverflow
Solution 3 - C#CheesoView Answer on Stackoverflow
Solution 4 - C#dss539View Answer on Stackoverflow
Solution 5 - C#zneakView Answer on Stackoverflow
Solution 6 - C#T.K.View Answer on Stackoverflow
Solution 7 - C#DavidView Answer on Stackoverflow