Search code examples
c#castlecastle-dynamicproxydynamic-proxy

How do you give a C# Auto-Property a default value in DynamicProxy?


namespace ConsoleApplication15
{
  using System;
  using Castle.DynamicProxy;

  public class Test
  {
    private SubTestClass subTestClass;

    public string Status
    {
      get
      {
        return this.subTestClass.SubStatus;
      }

      set
      {
        this.subTestClass.SubStatus = value;
      }
    }

    public int Data { get; set; }
  }

  public class SubTestClass
  {
    public string SubStatus { get; set; }
  }

  public class Program
  {
    public static void Main(string[] args)
    {
      var proxyGenerator = new ProxyGenerator();
      var testObject = proxyGenerator.CreateClassProxy<Test>();
      if (testObject.Status != null)
      {
        Console.WriteLine("Working");
      }
    }
  }
}

I have the following code and I want to set the Status default value to Empty string. When I run the following code the Status string is always Null and thrown A null exception!!

testObject.Status this shall return an empty string and not thrown an exception.


Solution

  • I found a soultion for the problem with IInterceptor I can create my custom result. Thanks for help!

    namespace ConsoleApplication15
    {
      using System;
      using Castle.DynamicProxy;
    
      public class Test
      {
        private SubTestClass subTestClass;
    
        public virtual string Status
        {
          get
          {
            return this.subTestClass.SubStatus;
          }
    
          set
          {
            this.subTestClass.SubStatus = value;
          }
        }
    
        public int Data { get; set; }
      }
    
      public class SubTestClass
      {
        public string SubStatus { get; set; }
      }
    
      public class Program
      {
        public static void Main(string[] args)
        {
          var proxyGenerator = new ProxyGenerator();
    
          var testObject = proxyGenerator.CreateClassProxy<Test>(new MyInter());
    
    
          if (testObject.Status != null)
          {
            Console.WriteLine("Working");
          }
        }
    
      }
    
      public class MyInter : IInterceptor
      {
        public void Intercept(IInvocation invocation)
        {
          if (invocation.Method.ReturnType == typeof(string))
          {
            invocation.ReturnValue = string.Empty;
          }
        }
      }
    }