Home > Back-end >  C# Custom attribute for handling null case
C# Custom attribute for handling null case

Time:01-23

I have several method that always check for null in the param for type "User". Instead of me having to write this pattern many times I want to utilize C# attribute.

public bool HasPendingBasket(User user)
{
    if (user == null)
    {
        return false;
    }

    // Code ..

}

public void AddUser(User user)
{
    if (user == null)
    {
        return;
    }

    // Code ..

}

// Many more methods like above

I wonder if that can be written into something like this:

public bool HasPendingBasket([NotNullReturn(false)] User user)

public void AddUser([NotNullReturn(null)] User user)

// Or 

[NotNullReturn(false)]
public bool HasPendingBasket(User user)

[NotNullReturn(null)]
public void AddUser(User user)

I read in the Microsoft docs and they mentioned

However, any attribute you create acts only as metadata, and doesn't result in any code within the attribute class being executed. It's up to you to act on that metadata elsewhere in your code (more on that later in the tutorial).

Here

So it sounds like attribute cannot do what I am looking for because it only act as a metadata. I wonder if my understanding is correct.

Also if is correct is there a better way to do a null check without having to write that pattern everywhere?

CodePudding user response:

I think what you need is the Null Object pattern.

CodePudding user response:

You are looking for a paradigm called Aspect-Oriented Programming (AOP) and specifically the interceptor pattern.

If you use autofac as your Dependency Injection container then you get this "for free". Autofac documentation

However under-the-hood this uses Castle DynamicProxy so you could roll your own with the built-in container. Writing a proxy handler to intercept and check for any attributes on the intercepted class/method. Castle documentation

  •  Tags:  
  • Related