Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6229187
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T09:31:19+00:00 2026-05-24T09:31:19+00:00

Say I have some method like so: public void Method<T>(Func<T> func) { … }

  • 0

Say I have some method like so:

public void Method<T>(Func<T> func)
{
...
}

Is there any way that I can use the Expression API and effectively inject some code to run before the code in the passed in Func runs? Meaning, in my method, I won’t actually execute the Func, rather I’ll be assigning it some property of an object that will invoke that Func. I just want to have some code run before the passed in code runs. Also, would it be possible for my code to “return” from the Func, so that the passed in code never runs?

EDIT: OK, I was afraid that wasn’t enough. Here’s what I’m trying to do. Using Moles, you can stub out any call made within your code. So say I have some untestable code that calls a static method like so:

FileSystem.ReadAllText(string fileName);

moles will create a stub/mole object (whatever the terminology is) which I can then use to stub out the method for, so when my code calls ReadAllText, it’ll call my stub:

MFileSytem.ReadAllTextString = s => return "content";

Very cool stuff, however I’m trying to expand on this idea, so that I can use it similiar to a typical Mocking framework (like Moq) so that I can stub out that method only when the passed in parameters is a certain value, or possibly to verify that a method is only called once etc. Here’s what I have so far:

STILL VERY VERY ROUGH!!

    public static class Extensions
    {
        public static void TestWithMoles<T, U, V>(this T item, Expression<Func<U, V>> expression, MolesDelegates.Func<U, V> stub)
        {
            var methodCallExpression = expression.Body as MethodCallExpression;
            if (methodCallExpression != null)
            {
                var method = methodCallExpression.Method;
                var returnType = method.ReturnType.Name;
                var assemblyName = method.DeclaringType.Assembly;
                var assmebly = GetMolesAssmeblyName(assemblyName.GetName().Name);
                var type = assmebly.GetTypes().FirstOrDefault(t => t.Name == "M" + method.DeclaringType.Name);
                var property = type.GetProperties(BindingFlags.Static | BindingFlags.Public).FirstOrDefault(p => p.Name == method.Name + returnType);
                property.SetValue(item, stub, null);
            }
        }

        private static Assembly GetMolesAssmeblyName(string assemblyName)
        {
            var entryAssembly = Assembly.GetExecutingAssembly();
            foreach (var assembly in entryAssembly.GetReferencedAssemblies())
            {
                if (assembly.Name == assemblyName)
                {
                    continue;
                }

                if (assembly.Name.Contains(assemblyName) && assembly.Name.Contains(".Moles"))
                {
                    return Assembly.Load(assembly.FullName);
                }
            }

            return null;
        }
    }

The idea now is, if I have a class like this:

public class TestReader
{
    public string Content { get; private set; }

    public void LoadFile(string fileName)
    {
        var content = FileSystem.ReadAllText(fileName);
        if (!content.StartsWith("test"))
        {
            throw new ArgumentException("invalid file");
        } 
        this.Content = content;
    }
}

I can now do this:

    [TestMethod]
    [HostType("Moles")]
    public void CheckValidFilewithMoles()
    {
        //arrange
        var fileName = "test.txt";
        var content = "test";

        //act
        var test = new TestReader();
        test.TestWithMoles<TestReader, string, string>(s => FileSystem.ReadAllText(s), s =>
                                                                                            {
                                                                                                Assert.IsTrue(s == fileName);
                                                                                                return content;
                                                                                            });
        test.LoadFile(fileName);
        //assert
        Assert.AreEqual(content, test.Content);
    }

So far so good, but I haven’t accomplished anything yet. What I WANT to do is, in my extension method, when I do this:

            property.SetValue(item, stub, null);

which will set the Moles delegate to whatever is passed in, I want to “inject” some code beforehand, so that I can see what the values are that are being passed in, I can add some data to some dictionary to keep track of the count of method calls, etc.

Hope that makes more sense now…

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T09:31:19+00:00Added an answer on May 24, 2026 at 9:31 am

    Why don’t you just wrap it before assigning it to the property ?

    Func<T> myProp = () => 
    { 
      //run your code here
      return func();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Let's say I have a function that looks like this: public void saveBooking(/* some
Let's say you have a business logic method that can perform some operation across
Let's say I have a subroutine/method that a user can call to test some
Say I have some code like namespace Portal { public class Author { public
Say I have a method public void PrintStuff(string stuff, Color color, PageDimensions dimensions) {
Lets say I have a WCF service that a client can use to receive
Lets say i have the following code private Func<T> _method; public void SetExecutableMethod<T>(Func<T> methodParam)
Say I have some windows method and a struct: struct SomeStruct{ int foo; int
Let's say I have some_value = 23 I use the Integer 's times method
Say I have some 10 categories that I need to reference in a web

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.