Skip to content
Igor Tkachev edited this page May 20, 2016 · 1 revision

Home / Aspects

This attribute allows checking a virtual or abstract method parameter if it is null at runtime. BLToolkit type builder will override methods with NotNull parameters and emit code for checking null value at the beginning of the method.

NotNull.cs

using System;

using NUnit.Framework;

using BLToolkit.Aspects;
using BLToolkit.Reflection;

namespace HowTo.Aspects
{
    [TestFixture]
    public class NotNullTest
    {
        public abstract class TestObject
        {
            public virtual void Foo1(string str1, [NotNull]              string str2, string str3) {}
            public virtual void Foo2(string str1, [NotNull("Null")]      string str2, string str3) {}
            public virtual void Foo3(string str1, [NotNull("Null: {0}")] string str2, string str3) {}

            public static TestObject CreateInstance() { return TypeAccessor<TestObject>.CreateInstance(); }
        }

        [Test, ExpectedException(typeof(ArgumentNullException))] // Error message is localized by framework.
        public void Test1()
        {
            TestObject o = TestObject.CreateInstance();

            o.Foo1("str1", null, "str3");
        }

        [Test]
        [ExpectedException(typeof(ArgumentNullException), ExpectedMessage="Null")]
        public void Test2()
        {
            TestObject o = TestObject.CreateInstance();

            o.Foo2("str1", null, "str3");
        }

        [Test]
        [ExpectedException(typeof(ArgumentNullException), ExpectedMessage="Null: str2")]
        public void Test3()
        {
            TestObject o = TestObject.CreateInstance();

            o.Foo3("str1", null, "str3");
        }
    }
}

BLToolkit type builder will generate the following for the class above:

[BLToolkitGenerated]
public sealed class TestObject : NotNullTest.TestObject
{
    public override void Foo1(string str1, string str2, string str3)
    {
        if (str2 == null) throw new ArgumentNullException("str2");

        base.Foo1(str1, str2, str3);
    }

    public override void Foo2(string str1, string str2, string str3)
    {
        if (str2 == null) throw new ArgumentNullException("str2", "Null");

        base.Foo2(str1, str2, str3);
    }

    public override void Foo3(string str1, string str2, string str3)
    {
        if (str2 == null) throw new ArgumentNullException("str2", "Null: str2");

        base.Foo3(str1, str2, str3);
    }
}
Clone this wiki locally