Reputation: 17003
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.
Upvotes: 3
Views: 305
Reputation: 17003
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;
}
}
}
}
Upvotes: 0
Reputation: 5596
To give auto implemented properties a default value, you'd have to do it in the constructor or something like:
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
var proxyGenerator = new ProxyGenerator();
var testObject = proxyGenerator.CreateClassProxy<Test>();
Console.WriteLine(
testObject.Status != null
? "Working"
: "no....");
}
}
public class Test
{
private SubTestClass subTestClass = new SubTestClass();
public string Status
{
get
{
return this.subTestClass.SubStatus;
}
set
{
this.subTestClass.SubStatus = value;
}
}
public int Data { get; set; }
}
public class SubTestClass
{
public SubTestClass()
{
SubStatus = "";
}
public string SubStatus { get; set; }
}
Upvotes: 2