What is best possible way to handle Exception in Extension methods? That includes exception generated from method and also null exception caused by calling extension method on null object.
Is it good to handle before calling extension method in proper business functionality or method should take care about exception.
Just to give idea here is code sample
class ABC
{
private readonly string name;
public ABC(string name)
{
this.name = name;
}
public string Name { get { return this.name; } }
}
internal static class ABCExtension
{
internal static void GetName(this ABC abc)
{
Console.WriteLine(abc.Name);
}
}
class Program
{
static void Main(string[] args)
{
ABC abc = new ABC("baam");
abc = null;
abc.GetName();
Console.Read();
}
}
This will generate null exception because abc object is null.
Adding details for more clarification here. I am confused between responsibility of class
I wanted to know whose responsibility is to handle exception. Extension class which is providing method or class which is using it?
Please let me know if any further details needed.
Arguments passed to extension methods, are like argument to regular methods. This included the first argument of the extension method (with
thisbefore the type name). If your method enforces any rule on the input parameters, it should check for them. And if there is a condition that should be handled by calling method, let the exception raise to the calling method.By the way, alwasy check for nulls and don’t let
NullReferenceExceptionhappen.NullReferenceExceptionmeans that there is a bug in your code.